passing parameters through link_to

1,733 views
Skip to first unread message

TTDaVeTT

unread,
Dec 6, 2007, 3:07:16 AM12/6/07
to Ruby on Rails: Talk
Is it possible to pass parameters through link_to that will be used by
the controller that link_to directs to? Specifically I have this
code:
<% for user in @users -%>
<%= link_to user.screen_name, {:action => "index", :controller =>
"users", :user_id => user.id } %>
<% end %>

Is it possible to use the parameter at the end of link_to(:user_id =>
user.id) to initialize a hash @user using the user_id?

This is the index action in the users controller:
def index
@user = User.find(:all, :conditions => { :id => :user_id })
end

I dont know if this makes sense but ultimately I am trying to link to
a profile and have that profile be filled with the user that matches
the id of the link that is clicked. So I am trying to pass the id of
the user through link_to and use that id in the index action above to
populate a hash with the corresponding user. Im not sure if this is
the way to go about it. Ive been stuck on this for a while, so any
input is much appreciated. Thanks, Dave

Frederick Cheung

unread,
Dec 6, 2007, 4:58:28 AM12/6/07
to rubyonra...@googlegroups.com

On 6 Dec 2007, at 08:07, TTDaVeTT wrote:

>
> Is it possible to pass parameters through link_to that will be used by
> the controller that link_to directs to? Specifically I have this
> code:
> <% for user in @users -%>
> <%= link_to user.screen_name, {:action => "index", :controller =>
> "users", :user_id => user.id } %>
> <% end %>
>
> Is it possible to use the parameter at the end of link_to(:user_id =>
> user.id) to initialize a hash @user using the user_id?
>
> This is the index action in the users controller:
> def index
> @user = User.find(:all, :conditions => { :id => :user_id })
> end

Either i'm horribly confused or you just need to do params[:user_id].
Typically though you'd just do

<%= link_to user.screen_name, {:action => "index", :controller =>

"users", :id => user.id }

and access it via params[:id]

Fred

ebrad

unread,
Dec 6, 2007, 10:42:07 AM12/6/07
to Ruby on Rails: Talk
It sounds like to me that you just want to be able to have a user
profile page with that particular user's info listed. Change your
loop to this:

<% for user in @users -%>
<%= link_to %Q{#{user.screen_name}}, {:controller =>
"users", :action => "index", :id => user.id } %>
<% end %>

Then, what you need to do is create another action in your 'users'
controller, for example, 'profile' that finds the params/attributes
for that user record.

Add this to your 'users' controller:

def profile
@user = User.find(params[:id])
end

Then, create a view called profile.rhtml. Once you do that you can
call upon any of the user's attributes with <%= @user.method_name %>
(e.g. @user.screen_name, @user.email, etc.).
Reply all
Reply to author
Forward
0 new messages