Pavel
Pavel

Reputation: 4410

cant pass param through link_to (rails)

I have a problem with passing params. in show view i have

=link_to "Send message", {:controller => "users", :action => "send_message", :user_id => @user.id}

and my users_controller have method

def send_message
    @user = User.find(params[:user_id])
    @message=Message.new
    redirect_to send_message_path
end

and my show method

def show
    @user = User.find(params[:id])
    @post=Post.new
    @[email protected](:page => params[:page],:per_page => 10)  
  end

but i have and error after clicking on link

Couldn't find User without an ID

in that line, in send_message method

 @user = User.find(params[:user_id])

what i am doing wrong? i read a lot examples about this , but it doesnt work(

Thanks in advance!!!

Upvotes: 0

Views: 1803

Answers (3)

nathanvda
nathanvda

Reputation: 50057

In your routes you should write:

resources :users do
  post :send_message, :on => :member
end

And in your view you write:

= link_to "Send Message", send_message_user_path(@user)

This will use id instead of user_id. So in your controller you need to use params[:id] as well.

Imho this is cleaner than @fl00r solution, because it is a member method, not a collection.

But I am a bit confused as to why you would have that method inside the controller at all. Because the only thing it does is redirect to the send_message_path anyway. The instance variables you set are all lost then. So instead in your view write this:

= link_to 'Send message', send_message_path(:user_id => @user.id)

And this will send you to the correct controller straightaway (where you will have to retrieve the user).

Also your show method could use some work: you should define a has_many :posts in your User model.

Upvotes: 0

fl00r
fl00r

Reputation: 83680

=link_to "Send message", [:send_message, @user]

and in your routes:

resources :users do
  post :send_message, :on => :collection
end

Upvotes: 1

nheinrich
nheinrich

Reputation: 1841

What happens if you try to change :user_id to :id, like this

=link_to "Send message", {:controller => "users", :action => "send_message", :id => @user.id}

def send_message
    @user = User.find(params[:id])
    @message=Message.new
    redirect_to send_message_path
end

If that works it's because your route isn't set up to use a :user_id param. If it doesn't it would help to know more about your route.

Upvotes: 1

Related Questions