Các mối quan hệ khai báo trong Couple
sẽ trông như thế này:
class Couple
named_scope :with_people, { :include => [:first_person, :second_person] }
belongs_to :first_person, :class_name => 'Person'
belongs_to :second_person, :class_name => 'Person'
end
#usage:
Couple.with_people.first
# => <Couple ... @first_person: <Person ...>, @second_person: <Person ...>>
Những người trong Person
phụ thuộc vào việc một Person
thể là một phần của nhiều hơn một Couple
. Nếu một Person
chỉ có thể thuộc về một Couple
và không thể là "đầu tiên" Person
trên một và Second
ngày khác, bạn có thể muốn:
class Person
has_one :couple_as_first_person, :foreign_key => 'first_person_id', :class_name => 'Couple'
has_one :couple_as_second_person, :foreign_key => 'second_person_id', :class_name => 'Couple'
def couple
couple_as_first_person || couple_as_second_person
end
end
Nếu một Person
có thể thuộc về một vài Couple
s, và có có cách nào để nói cho dù họ là những "đầu tiên" hay "thứ hai" trong bất kỳ Couple
nhất định, bạn có thể muốn:
class Person
has_many :couples_as_first_person, :foreign_key => 'first_person_id', :class_name => 'Couple'
has_many :couples_as_second_person, :foreign_key => 'second_person_id', :class_name => 'Couple'
def couples
couples_as_first_person + couples_as_second_person
end
end
Nguồn
2010-01-25 22:56:57
Nếu bạn đang sử dụng Rails, tại sao sẽ khóa chính trên mô hình Person là "Person_Id "và không chỉ" id "? – tfwright
Tôi đã thay đổi tên của các mô hình của mình cho bài đăng này vì tôi muốn giữ tên trên internet. Nó phải là 'id' nhưng đó không phải là một sửa chữa khó khăn. Chỉ cần sử dụng 'set_primary_key'. – user94154