开发者

Rails 3: update multiple parents when creating a child object on one of the parent's show

开发者 https://www.devze.com 2023-03-21 09:10 出处:网络
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. E

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消