While reading other peoples controllers code and some other resources, I met this kind of code a lot:
def create
if #record.save
redirect_to #record
else
respond_to do |format|
format.html {render :new}
format.json {render #record.errors}
end
end
But now, just clicking my app pages for fun (this was not covered by rout testing at all), I found out - if you click submit on invalid form, you will have form rendered and current path as /records. But if you hit reload page, this leads to an error:
No route matches GET /records
In my case, I don't have index action, or you will be redirected to index page, which is also rather inconvenient.
Is there any other way of being redirected back to /new but without loosing form inputs or error messages, as it happens with render?
Can I do something like this?
redirect_to new_record_path
respond_to do |format|
format.json {render #record}
end
render loads a view without calling another action. The data from the action containing the render call is used to render that view. That is why the form data can be displayed in that view.
redirect_to starts a new request that calls the action associated with the route. Since a new action is called, the data from the previously called action is not available to the view that the client is directed to.
Related
Right now, I have a rails ajax request on submission of a form, which has the following success code:
if #event.save
...
respond_to do |format|
format.js { render 'draw_calendar' }
format.html { redirect_to show_calendar_path }
end
end
I need to add some code that, if a new flag is set on the form, will spawn the creation of a new, follow-up form for a different model that (of course) should be governed by a different controller. Thus what I want to do is, if #event gets saved successfully, check that flag (easy), and if it's set, redirect to another controller action. First, will that even work in the browser if it was an ajax request (format.js)? And second, will the browser then successfully render whatever gets sent back from the new controller action?
Yes, browser always follow redirect in ajax request
if #event.save
if #event.something?
redirect_to some_other_path(format: params[:format])
return
end
respond_to do |format|
format.js { render 'draw_calendar' }
format.html { redirect_to show_calendar_path }
end
end
If you need to detect redirect in javascript code I usually add custom header
response.headers['X-XHR-Current-Location'] = request.fullpath
So when I save a record in my Rails 4 app this happens. Here's some details:
I'm using the Ace editor.
The data attribute is no where in my model or app.
The form is a standard form_for (not remote).
The record does save successfully but then it redirects to this weird ass URL.
The code for the update is standard scaffold boilerplate.
# PATCH/PUT /pages/1
# PATCH/PUT /pages/1.json
def update
respond_to do |format|
if #page.update(page_params)
format.html { redirect_to #page, notice: 'Page was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #page.errors, status: :unprocessable_entity }
end
end
end
Anyone have any ideas? Probably something simple but I can't for the life of me figure this one out. Let me know if there's any other pertinent information I can share.
In your specific case (the one shown in your quickcast), Chrome is considering this a security risk because you're submitting a <script> element containing javascript that's being inserted into the renderable contents of the page using [Rails' built-in] asynchronous javascript.
To avoid this, you could:
Strip out the wrapping <script> tags using client-side logic before submitting the form, and then add them back in on the server before saving the record.
Disable Rails' built-in ajaxification of the update action in this controller, so that it submits through plain old HTML
Add an intermediary redirect page between form submittal and viewing the show action
I believe it is because your #page show view is rendering escaped HTML and Javascript. Chrome probably has heuristics to analyze the page and determine what type of document it is. Since it likely doesn't start with <html>, then Chrome assumes it is a data file with the data: protocol. Try rendering to a string and printing the results on the console:
http://guides.rubyonrails.org/layouts_and_rendering.html#using-render
puts render_to_string #page
See section 4.1.1 http://guides.rubyonrails.org/security.html#redirection
data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K
Please update your answer with the show view template, the show action, and the log from render_to_string.
I am trying to continue along the path I was lead down in this post: render show page on submit backbone.js + rails + rails-backbone gem
I am still trying to figure out what I describe in the first paragraph of that question. I was messing around in the firebug console. When I click submit from the root page everything works fine (except the app doesn't navigate to the newly created objects show page). The url changes to http://localhost:3000/#/x (where x is the id of the newly created object). When I click submit again, I get "500 Internal Server Error 22ms". This error comes in the Console > All window with a little red arrow next to it that (when clicked) drops down another section - upon with I click the "HTML" tab - and I get this error:
ActiveModel::MassAssignmentSecurity::Error in UsersController#update
Can't mass-assign protected attributes: created_at, id, updated_at
I think I may have located the issue for this error - I just don't know what to do to fix it. What I think is going on is that I have two different controllers (a home controller, and a users controller) - and both of their index actions define the same thing, here is my users controller index action:
class UsersController < ApplicationController
# GET /users
# GET /users.json
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end
...
end
Here is my home controller index action:
class HomeController < ApplicationController
def index
#users = User.all
end
end
So as you can see, what I think is going on is that when I click submit the first time (from the home page) #users gets set, and the app gets navigated to the new user's show page (although it doesn't which again - ties this all back to my first question - the url changes, but the content of the page does not, the link for my first question is above).
After the url changes to the show page url (without loading the content), I tried submitting another user form with unique input and I get the mass-assign error above. This seems to be because #users has already been set by the home controller...so that when it is called again from the users controller (upon the second submit) it can't be assigned.
How would I fix this? I need both the home controller and the users controller to be able to use #users...I think. And, tying everything back to to my first question here: render show page on submit backbone.js + rails + rails-backbone gem
Can I do something from within the home controller that redirects the newly created user to the show page (maybe in the create, or update method or users controller/or index method of home controller)? Might this solve the issue I have with redirection to the show page from the root page? All the relevant backbone.js (and my root index.html.erb file) code is posted in my first question...please refer to it as it will fill you in on all the backbone details, and what I am really trying to do.
THANKS!
UPDATE
Here is the update action in my users controller (where the error is supposedly coming from):
def update
#user = User.find(params[:id])
respond_to do |format|
if #user.update_attributes(params[:user])
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
You are not supposed to send created_at and updated_at attributes to server.
You should inspect parameters you are sending and make sure you are not sending these.
By the way, did my other answer help you?
You should not insert or add created_at, id, updated_at these are generated automatically .......
Here I have a scaffold for clients, and in the create method in ClientsController,
if #client.save
redirect_to #client
else
render :action => "new"
end
Here what it means to redirect to an instance variable of Client class?
Also, in else, render renders the view for new if save fails. However, how does the controller keep the original input at the same place? (For example I fill the form and send it but fail to proceed, so it takes me back to the new client page with my original input at the right place.)
redirect_to #client redirects to the clients/show/1 directory. where 1 is the id of client.
and render :action => "new" render the new action, for more detail see http://guides.rubyonrails.org/layouts_and_rendering.html
For the code below, what happens if replacing redirect_to with render or vise verse?
def create
#product = Product.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to(#product, :notice => 'Product was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
It seems OK replacing one with the other in code above. Is there a place where only redirect_to or render has to be used? Render does nothing but rendering a view. Redirect_to sends 302 request to server and current parameters are lost after redirecting.
Thanks.
If you're using render, when the user refreshes the page, it will submit the previous POST request again. This may cause undesired results like duplicate purchase and others.
But if you're using redirect_to, when the user refreshes the page, it will just request that same page again. This is also known as the Post/Redirect/Get (PRG) pattern.
So the place where redirect_to should be used is when you're doing a HTTP POST request and you don't want the user to resubmit the request when it's done (which may cause duplicate items and other problems).
In Rails, when a model fails to be saved, render is used to redisplay the form with the same entries that was filled previously. This is simpler because if you use redirect, you'll have to pass the form entries either using parameters or session. The side effect is that if you refresh the browser, it will try to resubmit the previous form entries. This is acceptable because it will probably fail the same way, or if it's successful now, it was what the user should expect in the first place anyway.
For more in depth explanation about render and redirect, you should read this article.
When you redirect you will generate a new request that hits a controller method, render just renders the associated view. You use render in the create because you want to keep the state of the model object if the save fails so that you can render info about its errors. If you tried to redirect to the new_product path you would create a new model object and loose all the form data the user entered and any errors etc etc
EDIT (with some more info):
An example of a situation where you MUST use redirect_to is if your view template uses instance variables that are not initialized in the controller method you are redirecting from. So you probably could not call render {:action => 'index'} in your create method because the index template probably makes use of a #products variable but your only initialized #product so it would cause an exception
Here is a complete list of what the two methods do that I follow:
1) redirect_to will issue an HTTP 302 status code by default. A 302 redirect is a temporary change and redirects users and search engines to the desired page for a limited amount of time until it is removed. You can optionally specifiy a 301 status code to redirect_to. A 301 status code is used when any page has been permanently moved to another location. Users will now see the new page as it has replaced the old page. This will change the URL of the page when it shows in search engine results.
2) redirect_to will issue a new HTTP request, since it is redirects to a different controller action or URL. You should not make the browser need to make a fresh call unless you really have to, so always question when you are using redirect_to and if it is the right thing, or perhaps a render would be better.
- redirect_to will cause any automatic template rendering of the current action to be skipped.
3) render will issue an HTTP 200 status code by default ( but with an invalid ActiveRecord object, you may want to change this to 422 unprocessable entity). The HTTP 200 OK success status response code indicates that the request has succeeded. The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity nd the syntax of the request entity is correct but was unable to process the contained instructions.
4) render will render a template and any instance variables defined in the controller action will be available in the template. Of course, instance variables will not be available if the subsequent action that redirect_to invokes. IMPORTANT POINT: Redirect hits the controller while Render does not, so if you render a different template, it will not hit the action associated with that template and so those instance variables will not be available!
5) With render, use flash.now, instead of the normal flash.
flash.now[:error] = "There was a problem"
# not
flash[:error] = "There was a problem"
6) If you don't, then the flash message may not show up on the page that's rendered, and it will show up on the next page that's visited.
7) render will not cause the current action to stop executing! redirect_to will not cause the current action to stop executing! You need to invoke 'return' if you need to bypass further execution of code in the action! In the below code, there is an explicit render at the bottom and so you must do a return to avoid an error of redirect and render both being present:
def update
#record = Record.new(record_params)
if #record.save
flash[:success] = "record was successfully saved"
redirect_to records_path
return
end
flash.now[:error] = "please fix the problems in the record"
render :edit
end
Another option:
def update
#record = Record.new(record_params)
if #record.save
flash[:success] = "record was successfully saved"
redirect_to records_path
else
flash.now[:error] = "please fix the problems in the record"
render :edit
end
end
8) The flash message provides a way to pass temporary primitive-types (String, Array, Hash) between actions. Anything you place in the flash will be exposed to the very next action and then cleared out. This is a great way of doing notices and alerts:
class PostsController < ActionController::Base
def create
# save post
flash[:notice] = "Post successfully created"
redirect_to #post
end
def show
# doesn't need to assign the flash notice to the template, that's done automatically
end
end
show.html.erb
<% if flash[:notice] %>
<div class="notice"><%= flash[:notice] %></div>
<% end %>
Since you can have both notices and alerts in the flash, you can display both notices and alerts this way:
<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "flash #{key}" %>
<% end %>