1

I am new to rails and trying to learn now so hopefully someone can help.

I have 3 models for User, Opinion and Vote with one-to-many relationships. Each user has_many :opinions and has_many :votes. Each opinion has_many :votes and belongs_to :user. Each vote belongs_to user and belongs_to opinion. Votes table has columns for :decision (boolean), :opinion_id and :user_id. Opinions table only has :content column.

My use case is that a user adds an opinion and then other users can either agree or disagree with it when viewing each opinion (show view).

In Opinion show view I want to have two submit buttons with "Agree" and "Disagree". When a user submits a vote I need to create this vote (true or false) and update both user_id and opinion_id fields of the votes table. I managed to do it for each parent individually but not both for the same vote. Any help would be much appreciated.

Evgeny
  • 13
  • 3
  • If the vote is just "Agree" or "Disagree" I would propose not making it a separate model. Think of it as an attribute on an Opinon model. `attr_accessible :vote`. Then update_attribute when the user clicks on Agree or Disagree submit buttons. If you want to keep the Vote model, think of separating it with the User models, so that `User has_many :opinions` and `Opinion has_many :votes`, but Vote does not belong_to User. As far as I understand User can have no votes for no opinion. – Alexei Danchenkov Jul 20 '11 at 09:55
  • Thanks for your suggestion, although, I don't think it will work in my particular case. I need to track users' votes while the opinions on which they vote do not belong to those users, i.e. that opinion belongs to another user and and it has many votes from other users. – Evgeny Jul 20 '11 at 10:55

1 Answers1

0

Include both ids as hidden fields.

Opinion show view:

<%= form_for(@vote) do |f| %>
<%=   f.hidden_field :user_id, :value => @user.id %>
<%=   f.hidden_field :opinion_id, :value => @opinion.id %>
<%=   submit_tag 'Agree', :name => 'agree_button' %>
<%=   submit_tag 'Disagree', :name => 'disagree_button' %>
<% end %>`

Vote Controller:

def create
  @vote = Vote.new(params[:vote])
  if params[:agree_button]
    @vote.agreement = 1
  elsif params[:disagree_button]
    @vote.agreement = -1
  end
  flash[:notice] = "Thank you for your vote." if @vote.save
  redirect_to( opinion_path( @vote.opinion_id )) 
end
Alexei Danchenkov
  • 2,011
  • 5
  • 34
  • 49