Rails 4 acts_as_votable没有路由匹配/缺少必需的密钥错误

时间:2014-10-29 14:24:45

标签: ruby-on-rails ruby

我正在使用acts_as_votable插件,我不断收到此错误:

No route matches {:action=>"upvote", :controller=>"posts", :id=>nil} missing required keys: [:id]

我正在回答这个问题的答案:acts_as_votable thumbs up/down buttons

我尝试按照此处的建议将.id添加到视图中:Getting a strange error on my routes, "missing required keys" rails 4但后来我收到此错误:

undefined method `id' for nil:NilClass

这是我的代码:

post_controller:

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

路线:

resources :posts do
  member do
    get 'like' => 'posts#upvote', as: :upvote
  end
end

视图:

<% @posts.each do |post| %>
  <%= post.user.name %><BR><BR>
  <%= post.post_content %><BR><BR>
  <%= link_to "like", upvote_post_path(@post), method: :put %>
<% end %>

1 个答案:

答案 0 :(得分:2)

你应该:

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

发生错误是因为您应该使用post块变量,而您尝试使用@post实例变量,该变量未设置,因此评估为nil