ruby on rails表之间的关系,一个表中的多个字段与另一个表相关

时间:2011-05-11 13:50:45

标签: ruby-on-rails

我有2个表:人员和批次

批处理有3个与人员表相关的字段:主管,创建者和修饰符。

所有3个字段都存储Person表的person_id。

我已在人员和批处理模型之间创建了以下关系。

class Batch < ActiveRecord::Base
    belongs_to :person, :foreign_key => "supervisor_id"
end

class Person < ActiveRecord::Base
    has_many :batches, :foreign_key => "supervisor_id"
end

因此,如果我执行'batch.person.PER_NAME',我将获得主管的姓名..但我如何继续获取创建者和修改者的详细信息?

非常感谢您提供的任何建议

1 个答案:

答案 0 :(得分:2)

听起来你想要3种不同的关系:

class Batch < ActiveRecord::Base
  belongs_to :supervisor
  belongs_to :creator
  belongs_to :modifier
end

然后您可以独立引用每个:     batch.supervisor     batch.creator     batch.modifier

或者,您可以在两者之间创建连接表,并随意添加和删除链接:

class Batch < ActiveRecord::Base
  has_many :person_batches
  has_many :people, :through => :person_batches, :source => :persons # something like that
end

class Person < ActiveRecord::Base
  has_many :batches, :through => :person_batches
end

class PersonBatches < ActiveRecord::Base
  belongs_to :person
  belongs_to :batch

  # Has a column called :person_type where you can specify
  # "supervisor," "creator," "modifier," etc. This would
  # also allow a batch to have multiples of each, if that's
  # useful. Otherwise, you can add validations around this.
end