【问题标题】:has_and_belongs_to_many and has_many_through between the same models?has_and_belongs_to_many 和 has_many_through 在同一个模型之间?
【发布时间】:2014-12-18 21:58:18
【问题描述】:

我有一个模型 person 和一个模型 group。有两种人:领导带队和参与者参与。我需要领导者和团体之间的 hbtm 关系以及参与者和团体之间的 has_many-relationship。是否可以通过在模型中提供某种条件(是领导者/是参与者)来使用相同的模型 person 来做到这一点?

class Person < ActiveRecord::Base
  has_and_belongs_to_many :groups
  has_many :participations
  has_many :groups, :through => :participations
  ...
end

我想用一个模型来做到这一点,person,因为用户要么是领导者,要么是参与者,但每个用户都应该是一个人,即User belongs_to :person

【问题讨论】:

  • 当一个领导有很多组时,我可以理解。但是确定一个团队有很多领导者吗?
  • 是的,我的小组可以有很多领导。想想组织一个小组的领导团队。

标签: ruby-on-rails has-many-through has-and-belongs-to-many


【解决方案1】:

你应该只为人设计一门课,而不是更多。您可以执行以下操作:

class Person < ActiveRecord::Base
  has_many :relations
  has_many :groups, :through => :relations
   ...
end

class Group < ActiveRecord::Base
  has_many :relations
  has_many :persons, :through => :relations
  ...
end

class Relation < ActiveRecord::Base
  belongs_to :person
  belongs_to :group
end

table 'relations' 应该在 person_id 和 group_id 旁边再有一个字段,称为“leader”,值应该是 true/false 或 1/0。因此,如果该组的人是领导者,则该值应为 1/true,否则为 0/false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多