实例变量不能通过私有方法分配

时间:2016-03-15 19:10:02

标签: ruby-on-rails ruby-on-rails-4

当我使用此链接时:

<%= link_to "upvote", post_upvote_path(post), method: :put %>

我收到错误:

  

未定义的方法`likes_by&#39;为零:NilClass   这是因为没有正确分配方法upvote中的变量@post。

  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在此控制器内的其他方法中正常工作。但是,在这种方法中它并没有。例如,如果我使用:

  def upvote
    @post = Post.first
    @post.liked_by current_user
    redirect_to @post
  end

相反,它会工作正常,除了它将首先发布的部分而不是单击链接的部分。解决这个问题的正确方法是什么?如何正确分配此变量以适用于单击upvote链接的帖子?

rake routes | grep posts输出:

enter image description here

我注意到这个方法有/ posts /:post_id ...而其他人使用:id。这可能是问题,我该如何改变呢?

4 个答案:

答案 0 :(得分:1)

在你的link_to中你传递的帖子......是在@posts循环的上下文中吗?投票完成后你在哪个页面上?

试试这个:

def upvote
  puts "params: #{params.inspect}"
  @post = Post.find(params[:id]) # if this isn't working check out that puts statement in the stack trace
  @post.liked_by current_user 
  redirect_to post_path(@post)
end

答案 1 :(得分:0)

路线文件中的

post_upvote /posts/:post_id/upvote而非post_upvote /posts/:id/upvote

实际上是这样的 当您将帖子传递给post_upvote_path方法时post_upvote_path( post)  在您的控制器中,由于您在路径文件中所写的内容,您想要params[:post_id]而不是params[:id]

def current_post
  current_user.posts.find_by(id: params[:post_id]) #post_upvote /posts/:post_id/upvote
end

答案 2 :(得分:0)

我发现了问题所在。在路径文件中,我需要嵌套成员方法,如下所示:

  resources :posts do
    member do
      put 'upvote', to: 'posts#upvote'
    end
  end

然后将视图更改为:

  <%= link_to "upvote", upvote_post_path(post), method: :put %>

控制器中的这个方法工作正常:

  def upvote
    @post = Post.find(params[:id])
    @post.liked_by current_user
  end

答案 3 :(得分:-1)

此:

<%= link_to "upvote", post_upvote_path(post), method: :put %>

应该成为:

<%= link_to "upvote", post_upvote_path(@post), method: :put %>
相关问题