I am confused about the main difference(s) among link_to
, redirect_to
and render
in Rails. anyone can please explain.
I actually just wrote a blog post about this. The most important bits are copied below (with modifications).
render
vs. redirect_to
render
and redirect_to
are the two ways that controller actions end (generally speaking). To understand how they work, let's review what controllers do in a Rails app:
GET /books/index.html
)books GET /books/index(.:format) books#index
)This last step occurs explicitly when you call render
or redirect_to
, or implicitly if you leave it out.
That is,
def index
@books = Book.all
end
is the same as
def index
@books = Book.all
render :index
end
render :index
says, ‘combine the data I've prepared (@books = Book.all
) with the books/index.html.erb
view template to generate a complete HTML document, then send that back to the client.’
redirect_to @book
says, ‘tell the client to start the whole process over again, issuing a new GET
request to url_for(@book)
.
If you omit both, the action will render a template with the same name as the action itself. In other words, you only need to call render
explicitly when the view template you want doesn’t match the action you’re rendering it from.
Note that not every controller action has a corresponding view template. Generally, #create
, #update
, and #destroy
(which are all routed to non-GET
HTTP requests) attempt to make some change to the database and then either redirect_to
some resource (if it succeeded) or re-render
the form that preceded it, along with any errors (if it failed).
As the official guides explain (emphasis mine),
These two methods [
render
andredirect_to
] represent the two basic action archetypes used in Action Controllers: Get-and-show and do-and-redirect. Most actions are variations on these themes.
render
vs. link_to
render
is also used within view templates themselves. Rather than generating a complete HTML document, it's used to insert a partial view template into a larger one. Here's the upshot:
_nav.html.erb
).render 'nav'
if you want to include the _nav.html.erb
partial from a view located in the same folder.render 'shared/nav'
if you want to include the partial at app/views/shared/_nav.html.erb
from any view in your project.link_to
is just a convenience method for inserting anchor tags (a href
tags) into your view templates. This is useful because a lot of the URLs you'll want to link to are other pages within your application, and those URLs can be referenced using objects or "helper methods", like so:
= link_to 'Back', books_path # renders as Back
= link_to 'View', @book # renders as View or similar