Uday's website
Published on Uday's website (https://uday.net)

Home > What is the difference between render and redirect? - Lesson learned 2

What is the difference between render and redirect? - Lesson learned 2 [1]

Submitted by uday [2] on September 16, 2020 - 12:06pm

-Redirect is a method that is used to issue the error message in case the page is not found or it issues a 302 to the browser. Whereas, render is a method used to create the content.

-Redirect is used to tell the browser to issue a new request. Whereas, render only works in case the controller is being set up properly with the variables that needs to be rendered.

-Redirect is used when the user needs to redirect its response to some other page or URL. Whereas, render method renders a page and generate a code of 200.

-Redirect is used as:
redirect_to: controller => ‘users’, :action => ‘new’

-Render is used as:
render: partial
render: new -> this will call the template named as new.rhtml without the need of redirecting it to the new action.

 

Why did all this started?

I noticed that following code using flash.now was not working. However, as per API documentation [3], it should have worked fine.

      flash.now[:warning] = "User cannot be deleted."
      redirect_to admin_users_path

However, following code without using .now did work.

      flash[:warning] = "User cannot be deleted."
      redirect_to admin_users_path

 

The reason is as follows based on ruby guide information [4]:

When redirecting use

flash[:warning] = "flash will make the message available to the next request"

When rendering use

flash.now[:warning] = "flash will make the message available to the same request"

 

 

Rating: 
Tags: 
Rails [5]

 Valid XHTML 1.0 StrictCreative Commons LicenseVerbatim copying and redistribution of this entire page are permitted provided this notice is preserved. All content on this website including archives (including text, photographs, audio files and any other original work), unless otherwise noted, is licensed under a Creative Commons License or later.


Source URL:https://uday.net/What-is-the-difference-between-render-and-redirect

Links
[1] https://uday.net/What-is-the-difference-between-render-and-redirect [2] https://uday.net/user/1 [3] https://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html [4] http://guides.rubyonrails.org/action_controller_overview.html#the-flash [5] https://uday.net/taxonomy/term/82