Are redirect_to and render exchangeable? - ruby-on-rails

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 %>

Related

Rails: practice of rendering new on invalid entry

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.

What does redirect_to #client mean?

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

On create error, should I render `new` or redirect to `new`?

Suppose I have something like this:
def new
#user = User.new
end
def create
#user = User.create(params[:user])
if #user.save
flash[:notice] = 'User created'
redirect_to :action => 'list'
else
flash[:error] = 'Some error here!'
render 'new'
end
end
I think the code is clear.
The problem here is, when the #user object is not saved successfully, should I render new (as above) or should redirect to new?
I know if redirect to new the data input by the user is lost, but if I render new, the URL will be /users/create instead of /users/new (which is ugly!).
You are correct in not using redirect. Redirect is loading an entirely new resource.
render however will keep your session data fresh, and depending on how your form is set up, should repopulate whatever data was inputted.
You mention:
I know if redirect to new the data input by the user is lost, but if I render new, the URL will be /users/create instead of /users/new (which is ugly!).
No, this is not true. If you say render 'new', it will go to the url users/new not create. Create as an action only handles POST requests to your controller, and generally never has a view associated with it. It will instead refer to the new action to handle any errors and displaying of forms.
The create action has this in common with the update action which does the same thing by handling only PUT requests, but refers to the edit action to handle the displaying of views.

Create action redirects to the wrong page?

When I check to see if my error message is working correctly, I notice my redirect goes to /businesses instead of /businesses/new after it POST (create action). I am using the regular RESTFUL routes but I need it to go back to /businesses/new on POST when their is an error. How can I do this?
This is my current code:
def create
#business = Business.new(params[:business])
if #business.save
redirect_to :back, :notice => "You have successfully added a new business."
else
render :action => 'new', :notice => "Please try again."
end
end
You should not redirect if the validation is failed. Here is what i should do to stay on the same page.
def create
#business = Business.new(params[:business])
if #business.save
redirect_to businesses_path
else
render :new
end
end
It is actually not a redirection. If you chech the html code generated for your form, you will see something like this:
<form accept-charset="UTF-8" action="/business"
class="new_business" id="new_business" method="post">
This means that the requested page to load is not the "/business/create" but the "/business". That is why you see it in the browser's address bar. This has nothing to do with your redirection in the create action. There you just render the previous form. This is not an error, it is actually working, maybe a little confusing, but that is not much of a problem, I think. With some javascript you can correct it if really needed.

Redirect to after successful ajax form

I've got a form with remote => true.
And right now my controller looks like:
# POST /items
# POST /items.json
def create
#item = #store.items.build(params[:item])
respond_to do |format|
if #item.save
format.html { redirect_to edit_admin_item_path(#item), :flash => {:success => "#{#item.name} was successfully created."} }
format.js { render :js => "window.location.href = ('#{edit_admin_item_path(#item)}');"}
format.json { render json: #item, status: :created, location: #item }
else
format.html { render action: "new" }
format.js { render :partial => 'fail_create.js.erb', :locals => { :ajax_errors => #item.errors.full_messages } }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
Which works but feels very clumsy. It also doesn't allow me to use a flash notice, which is sad time indeed.
Ideally I feel like I should be able to simply use "format.js { redirect_to...} or check against the request headers and redirect_to. Sheesh!
I'm not sure what the best solution is. Any advice would be super awesome, thanks in advance!
-- PS -- I know this has been asked somewhat before but to no avail: How to redirect after a successful AJAX form submission. There seems to many questions similar floating around, but no real solutions.
I think it might be impossible. The response to a Ajax request is processed by XMLHttpRequest. If a 3xx response is returned, XMLHttpRequest will follow the redirect itself, if the URL is of same origin. No matter how you set the headers, the browser cannot be aware of that. So the only way could be changing window.location with some Javascript.
I use a combination of Rails responders to generate my response messages and some content in my <action>.js file.
The content of — say update.js would look something like this:
// Checks if the article slug has changed.
// If it has the entire page should be reloaded at that new location.
<%= reload_if_slug_changed #article, params[:id] %>
// Displays the flash notices
// See ApplicationHelper#js_flash_response
<%= js_flash_response %>
Where the different methods are defined in some helper (in my case my ApplicationHelper). The content of the different methods are as follows:
def js_flash_response
if flash.now[:notice].present?
js = "$('#notice').html('#{flash.now[:notice]}').change();"
elsif flash.now[:alert].present?
js = "$('#alert').html('#{flash.now[:alert]}').change();"
end
end
def reload_if_slug_changed object, expected_value
"window.location.href = '#{url_for [:edit, object]}';" if object.slug != expected_value
end
The content of the flash messages are generated automatically by Rails responders and displayed with the now scope that deletes the from the flash hash, ensuring that if the user reloads (after the flash has been displayed) they will not reappear.
I don't believe that you should ever make a form pointing to a restful create action a remote one, because you would always expect critical redirect, so in my case I only need to redirect if the url slug has changed.
I hope that this helps. It's not a solution, but simply the way that I handled some of the same problems.
Best regards.
Under your scenario, here's how I would inject javascript into the page from a controller action. After you've completed the logic section of your action insert something like this:
render :update do |page|
page << "javascript_here"
end
This should allow you to insert you window.location or create a javascript flash method and call it when your create method executes correctly.
If you're looking to DRY up your controller actions, I would recommend looking into this Railscast about make_resourceful. Make_resourceful automagically performs each core activity for each action. It also allows you to tap into the hooks that they've created such as before :create, after :create, response_for :create, and after :create_fails. By using this gem, you can run code based on the success or failure of your methods and have finer grained control over them.
In addition to this, you should be able to initialize a create.js.erb and create_fails.js.erb in your view file, include a format.js without anything passed to it in your controller, and Rails will automagically run that file that contains javascript depending on if the controller action executed successfully.

Resources