【问题标题】:Setting up an association between Users and Bounties in Rails在 Rails 中设置用户和赏金之间的关联
【发布时间】:2015-09-03 00:36:17
【问题描述】:

与 Stackoverflow 上的工作方式类似,我正在设置一个应用程序,用户可以在其中发布赏金,其他用户可以自愿完成。

唯一的区别是用户选择执行赏金的人。因此,例如,如果创建了一个赏金并且三个人自愿完成它,那么创建者可以选择 1/3、2/3 或 3/3。

当一个赏金被创建时,它被认为是open,当用户选择一个正在进行时:in-progress,当完成时:complete >.

对于初学者,我将如何设置我的关联,其中用户是赏金的唯一所有者,但 其他 用户属于赏金但volunteers,如果选择成为participants。这应该作为一个自我参照的关联来完成吗?似乎设置两个新模型可能/可能不是多余的。

class User < ActiveRecord::Base
  has_many :bounties
end

class Bounty < ActiveRecord::Base
  belongs_to :user
end

至于赏金的状态,我应该在赏金表中设置三个不同的基于布尔值的列吗?

:open, :in_progess, :complete

【问题讨论】:

  • 您需要第三个模型作为要添加赏金的组件,您可以使用第三个模型创建through 关系

标签: ruby-on-rails ruby activerecord associations


【解决方案1】:

我会这样做:这未经测试,因此您可能需要调整选项。

User
  has_many :owned_bounties, :class_name => "Bounty", :as => :owner
  has_many :bounty_volunteers, :as => :volunteer
  has_many :volunteered_bounties, :through => :bounty_volunteers

Bounty 
  #owner_id, status(can be "open", "in_progress" or "complete")
  belongs_to :owner, :class_name => "User"
  has_many :bounty_volunteers
  has_many :volunteers, :through => :bounty_volunteers, :source => :volunteer
  has_many :participants, :through => :bounty_volunteers, :source => :volunteer, :conditions => ["bounty_volunteers.selected = ?", true]

#join table class
BountyVolunteer
  #bounty_id, volunteer_id, selected(bool)
  belongs_to :bounty
  belongs_to :volunteer, :class_name => "User"

因此,当您将用户添加为志愿者时,您就是在创建 BountyVolunteer 记录。如果他们升级为参与者,您正在编辑现有的 BountyVolunteer 记录。

【讨论】:

  • 对于用户模型中的第三个关联,volunteered_bounties 指的是什么?对于赏金模型,第二个关联has_many :bounty_volunteers 代表什么?两个have_many through 关联是否不处理这种所有权情况?
  • volunteered_bounties 是赏金和自愿为他们服务的用户之间的连接表/模型。这是一个“丰富的”连接,因为它记录了它们是否也被选中。
  • 我明白了。现在把它放在一起我遇到了这个错误:SQLite3::SQLException: no such column: bounties.owner_type: SELECT "bounties".* FROM "bounties" WHERE "bounties"."owner_id" = ? AND "bounties"."owner_type" = ?
  • 当我输入这样的内容时返回上述错误:user.owned_bounties
  • 看起来它认为bounty.owner 关联是多态的,这很奇怪。尝试将:foreign_key =&gt; :owner_id 添加到belongs_to :owner 关联。
猜你喜欢
  • 1970-01-01
  • 2016-08-30
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多