【问题标题】:Rails 4 acts_as_votable No route matches / missing required keys errorRails 4acts_as_votable 没有路由匹配/缺少必需的键错误
【发布时间】:2014-12-25 07:19:18
【问题描述】:

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

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

我正在关注这个 SO 问题的答案: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 %>

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    你应该有:

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

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

    【讨论】:

    • 谢谢!当我达到 50 个代表时,我会在我引用的原始问题中添加一个注释,以防其他人遇到这个问题。我会在 10 分钟内选择你的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多