Reputation: 5382
I'm going through Michael Hartl's tutorial at http://ruby.railstutorial.org/. It's basically a message board app where Users can post Messages and others can leave Replies. Right now I'm creating Users
. Inside the UsersController
things look like this:
class UsersController < ApplicationController
def new
@user = User.new
end
def show
@user = User.find(params[:id])
end
def create
@user = User.new(params[:user])
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
end
The author says that the following lines are equivalent. Which makes sense to me:
@user = User.new(params[:user])
is equivalent to
@user = User.new(name: "Foo Bar", email: "foo@invalid",
password: "foo", password_confirmation: "bar")
redirect_to @user
redirects to show.html.erb
. How exactly does that work? How does it know to go to show.html.erb
?
Upvotes: 9
Views: 6480
Reputation: 21
When you take a look of the source code of redirect_to
, you will notice that finally, it will return redirect_to_full_url(url_for(options), status),
try to call the url_for
function with an object, suppose you have an object is @article, url_for(@article), it will return like this:"http://localhost:3000/articles/11", that's will be a new request to this URL, then in your routing, you can also check the routes in your console by type in:
rake routes
article GET /articles/:id(.:format) articles#show
so that's why the redirect_to @article
will to go SHOW
action, and render in show.html.erb
. Hope answered your question.
Upvotes: 2
Reputation: 13404
This is all handled through the magic of Rail's restful routing. Specifically, there's a convention that doing a redirect_to
a specific object goes to the show
page for that object. Rails knows that @user
is an active record object, so it interprets that as knowing you want to go to the show page for the object.
Here's some detail from the appropriate section of the Rails Guide - Rails Routing from the Outside In.:
# If you wanted to link to just a magazine, you could leave out the
# Array:
<%= link_to "Magazine details", @magazine %>
# This allows you to treat instances of your models as URLs, and is a
# key advantage to using the resourceful style.
Basically, using restful resources in your routes.rb
file gives you 'shortcuts' for creating url's directly out of ActiveRecord objects.
Upvotes: 16
Reputation: 4097
I would suggest reading about Resource routing http://guides.rubyonrails.org/routing.html .
Upvotes: -4