简体   繁体   中英

Pass more than one association ID upon record creation

I currently have a model called Problem. this is associated to a user via belongs_to and a user has_many problems. Users can vote on the problems. With this I have a vote model with a belongs_to/index to both the problem and the user.

This code creates my vote, however It does not carry over the user ID as well. Eventually I want to so that a user can only vote on a problem once. How can I get it so it accepts two arguments upon creation instead of just the problem_id.

Conerns/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 %>

I suppose that you can get the id of the current user with current_user.id (if you're using Devise), and that there's a user_id column in the votes table (if not, create it via a migration), then you can write the action like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM