ruby on rails relationship between tables, multiple fields in one table related to another table
I have 2 tables: person and batch
A batch has 3 fields which relates to the person table: supervisor, creator and modifier.
All 3 fields store the person_id of the Person table.
I already created the fol开发者_运维技巧lowing relationship between the person and batch models.
class Batch < ActiveRecord::Base
belongs_to :person, :foreign_key => "supervisor_id"
end
class Person < ActiveRecord::Base
has_many :batches, :foreign_key => "supervisor_id"
end
So if i do 'batch.person.PER_NAME', i will get the supervisor's name..but how do i go on to get the creator and modifier details?
Many thanks for any suggestion provided
It sounds like you want 3 different relationships:
class Batch < ActiveRecord::Base
belongs_to :supervisor
belongs_to :creator
belongs_to :modifier
end
Then you can reference each one independently as: batch.supervisor batch.creator batch.modifier
Alternatively, you could create a join table between the two and arbitrarily add and remove linkages:
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
精彩评论