what is the difference between link_to, redirect_to, and render? what is the difference between link_to, redirect_to, and render? ruby ruby

what is the difference between link_to, redirect_to, and render?


link_to is used in your view, and generates html code for a link

<%= link_to "Google", "http://google.com" %>

This will generate in your view the following html

<a href="http://google.com">Google</a>

redirect_to and render are used in your controller to reply to a request.redirect_to will simply redirect the request to a new URL, if in your controller you add

redirect_to "http://google.com"

anyone accessing your page will effectively be redirected to Google

render can be used in many ways, but it's mainly used to render your html views.

render "article/show"

This will render the view "app/views/article/show.html.erb"

The following link will explain the redirect_to and the render methods more in detailhttp://guides.rubyonrails.org/layouts_and_rendering.html


From the Documentation:

Regarding rendering a view vs redirecting a request

. . . render tells Rails which view (or other asset) to use in constructing a response. The redirect_to method does something completely different: it tells the browser to send a new request for a different URL.

Regarding rendering a view

. . . render :action doesn't run any code in the target action . . .

Regarding redirecting a request

. . . Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.


Basically:

link_to is a helper method to generate URLs usually used in your views (.html.erb files)

render tells your controller to render a view without passing any data (say, from a form) to the next controller action.

redirect_to does a 302 page redirect, passing data (say, from a form) to either a controller action on your web app, or an external app (ex: google, facebook, a web article you liked, etc)


link_to is for use in ERB templates. It outputs a link to a specific path or url.

redirect_to is for use in controllers. It causes the client to request the specified path or url once the controller method exits.

render is also for use in controllers. It causes Rails to render the specified template.

redirect_to and render may only be called once in a given controller method.