Rails 3:在父对象之一上创建子对象时更新多个父对象

发布于 2024-11-25 08:35:23 字数 499 浏览 1 评论 0原文

我是 Rails 新手,现在正在尝试学习,希望有人能提供帮助。

我有 3 个具有一对多关系的用户、意见和投票模型。每个用户 has_many :opinionshas_many :votes。每个意见都有_many :votesbelongs_to :user。每个投票属于用户属于意见。投票表包含 :decision (boolean)、:opinion_id 和 :user_id 列。意见表只有:内容列。

我的用例是,用户添加意见,然后其他用户在查看每个意见(显示视图)时可以同意或不同意它。

在意见显示视图中,我想要两个带有“同意”和“不同意”的提交按钮。当用户提交投票时,我需要创建此投票(正确或错误)并更新投票表的 user_id 和 Opinion_id 字段。我成功地为每位家长单独做到了这一点,但没有为同一张投票同时做到这一点。任何帮助将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不必在意 2024-12-02 08:35:23

将两个 id 包含为隐藏字段。

意见显示视图:

<%= 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 %>`

投票控制器:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文