无法通过 link_to (rails) 传递参数
我在传递参数时遇到问题。在显示视图中我有
=link_to "发送消息", {:controller => “用户”,:操作=> "send_message", :user_id =>; @用户.id}
和我的 users_controller 有方法
def send_message
@user = User.find(params[:user_id])
@message=Message.new
redirect_to send_message_path
end
和我的 show 方法
def show
@user = User.find(params[:id])
@post=Post.new
@[email protected](:page => params[:page],:per_page => 10)
end
,但点击链接后我有错误
无法找到没有 ID 的用户
,在 send_message 方法中
@user = User.find(params[:user_id])
我做错了什么?我读了很多关于这个的例子,但它不起作用(
提前感谢!!!
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!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在你的路线中:
and in your routes:
如果您尝试将 :user_id 更改为 :id 会发生什么,就像这样
如果有效,那是因为您的路由未设置为使用 :user_id 参数。如果没有,更多地了解您的路线将会有所帮助。
What happens if you try to change :user_id to :id, like this
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.
在你的路由中你应该写:
在你的视图中你写:
这将使用
id
而不是user_id
。因此,在您的控制器中,您还需要使用 params[:id] 。
恕我直言,这比 @fl00r 解决方案更干净,因为它是成员方法,而不是集合。
但我有点困惑为什么你会在控制器中使用该方法。
因为它唯一做的就是重定向到
send_message_path
。那么你设置的实例变量就全部丢失了。因此,在您的视图中写下以下内容:这将立即将您发送到正确的控制器(您必须在其中检索用户)。
另外,您的
show
方法可能需要一些工作:您应该在您的User
模型中定义一个has_many :posts
。In your routes you should write:
And in your view you write:
This will use
id
instead ofuser_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: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 ahas_many :posts
in yourUser
model.