Reputation: 4706
What does the code
redirect_to @user
when used in a controller method, mean in Rails?
Where exactly does it redirect to? Does it redirect to a Users controller (If so, which method of the controller), or does it not go through the controller and instead go directly to a view?
Upvotes: 2
Views: 593
Reputation: 1071
it calls the show function of users like this
redirect_to user_path(@user)
important point : if we see the routes then :id is passed but here object is getting passed
which get converts into the id of the user by
def to_param self.id end
which is available in model and we can overwrite it to
so basically to conversion take place first
redirect_to @user => redirect_to user_path(@user)
then
@user => @user.id
Upvotes: 1
Reputation: 5625
This is the equivalent of writing
redirect_to user_path(@user)
More Rails magic at work here, for better or worse.
Upvotes: 2
Reputation: 6958
Basically it looks up a bunch of stuff about how your resource routes work
think of it like this
send("#{@user.class.name.underscore.downcase}_path", @user)
this is probably not the exact code but it should help you visualize whats actually going on.
The controller always runs, in this case it would be the show action of your users controller unless you have some funky router options.
rake routes
explains how the routes are laid out in this case show is
get /users/:id => users#show :as => "user_path"
the substitution from your incoming model works like this
a regex is created from your route
:id being a param
would match to inbound_object to the path function which is @user
:id is replaced with @user.id
Upvotes: 4
Reputation: 6516
From the redirect_to docs:
Redirects the browser to the target specified in options. This parameter can take one of three forms:
...
Record - The URL will be generated by calling url_for with the options, which will reference a named URL for that record.
And from the url_for docs:
Passing a record (like an Active Record or Active Resource) instead of a Hash as the options parameter will trigger the named route for that record. The lookup will happen on the name of the class. So passing a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as admin_workshop_path you’ll have to call that explicitly (it’s impossible for url_for to guess that route).
Upvotes: 2