不能通过私有方法分配实例变量 [英] Instance variable can't be assigned via private method
问题描述
当我使用此链接时:
<%= link_to "upvote", post_upvote_path(post), method: :put %>
我收到错误:
nil:NilClass 的未定义方法 `liked_by'这是因为方法 upvote 中的变量 @post 没有正确分配.
undefined method `liked_by' for nil:NilClass Which is caused because variable @post inside method upvote is not properly assigned.
def upvote
@post = current_post
@post.liked_by current_user
redirect_to @post
end
private
def current_post
current_user.posts.find_by(id: params[:id])
end
私有方法 current_post 在此控制器内的其他方法中工作正常.然而,在这个方法中它没有.例如,如果我使用:
private method current_post works fine in other methods inside this controller. However, inside this method it doesn't. For example If I used:
def upvote
@post = Post.first
@post.liked_by current_user
redirect_to @post
end
相反,它可以正常工作,除了它会赞成第一篇文章而不是点击链接的部分.解决这个问题的正确方法是什么?如何正确分配此变量以用于单击 upvote 链接的帖子?
instead, it would work fine, except for the part it would upvote first post instead of the one where link is clicked. What is the right approach to this problem? How do I assign this variable properly to work for post where upvote link is clicked?
rake 路线 |grep 帖子
输出:
我注意到这个方法有/posts/:post_id ... 而其他人使用 :id .这可能是问题所在,我该如何更改?
I noticed that this method has /posts/:post_id ... while others use :id . That might be the issue, how do I change it?
推荐答案
我找到了问题所在.在路由文件中,我需要像这样嵌套成员方法:
I found where was the problem. In routes file I needed to nest member method like this:
resources :posts do
member do
put 'upvote', to: 'posts#upvote'
end
end
然后将视图更改为:
<%= link_to "upvote", upvote_post_path(post), method: :put %>
控制器中的这个方法工作得恰到好处:
And this method in controller works just right:
def upvote
@post = Post.find(params[:id])
@post.liked_by current_user
end
这篇关于不能通过私有方法分配实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!