2014-10-29 100 views
-1

我使用的acts_as_votable插件,我不斷收到此錯誤:acts_as_votable thumbs up/down buttons軌道4 acts_as_votable沒有路由匹配/缺少必需的密鑰錯誤

我:

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

我從這個SO問題的答案如下嘗試添加.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

你應該有:

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

發生此錯誤是因爲您應該使用post塊變量,而您嘗試使用@post實例變量,該變量未設置,因此計算結果爲nil

+0

謝謝!當我到達50代表時,我會爲我引用的原始問題添加註釋,以防其他人遇到此問題。我會在10分鐘內選擇你的答案。 – MandyM 2014-10-29 14:31:10

相關問題