2014-04-26 58 views
0

我目前有一個名爲Problem的模型。這通過belongs_to和用戶has_many問題關聯到用戶。用戶可以對問題進行投票。有了這個我有投票模型與belongs_to /索引問題和用戶。創建記錄時通過多個關聯ID

此代碼創建我的投票,但它不會帶出用戶ID。最終我想讓用戶只能對問題進行一次投票。我怎樣才能得到它,所以它創建時接受兩個參數,而不僅僅是problem_id。

值得關注的問題/ Vote.rb

def upvote 
    @problem = Problem.find(params[:id]) 
    @problem.votes.create 
    redirect_to(problem_path) 
end 

的routes.rb

resources :problems do 
member do 
    post 'upvote' 
end 

index.html.erb

<%= button_to '+1', upvote_problem_path(problem), method: :post %> 

回答

0

我想你可以獲取當前用戶的id與current_user.id(如果您使用Devise),並且中有user_id列表(如果沒有,通過遷移創建它),那麼你可以寫這樣的動作:

def upvote 
    @problem = Problem.find(params[:id]) 
    @problem.votes.create :user_id => current_user.id 
    redirect_to problem_path(@problem) 
end 
+0

完美的作品。我的確在使用設計,並且在投票表上已經有了ID。非常感謝Baldrick。 – DMH

相關問題