与 Stackoverflow 上的工作方式类似,我正在设置一个应用程序,用户可以在其中发布赏金,其他用户可以自愿完成它。
唯一的区别是用户选择执行赏金的人。例如,如果创建了一个赏金并且三个人自愿完成它,那么创建者可以选择 1/3、2/3 或 3/3。
创建赏金后,当用户选择进行中:进行中,以及完成时:完成时,它被视为开放>.
对于初学者,我将如何设置我的关联,其中用户是赏金的唯一所有者,但其他用户属于赏金,但作为志愿者
,如果选择成为参与者
。这应该作为一个 self 参照关联来完成吗?看来设置两个新模型可能/可能不是多余的。
class User < ActiveRecord::Base
has_many :bounties
end
class Bounty < ActiveRecord::Base
belongs_to :user
end
至于赏金的状态,我应该在赏金表中设置三个不同的基于 bool 值的列吗?
:打开,:in_progess,:完成
最佳答案
我会做这样的事情:这没有经过测试,所以你可能需要调整选项。
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 记录。
关于ruby-on-rails - 在 Rails 中设置用户和赏金之间的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897288/