2010-01-24 21 views
7

我有一個模型,Couple,其中有兩列,first_person_idsecond_person_id和另一種模式,Person,其主鍵是person_id並且具有柱name的ActiveRecord的has_many其中表A兩列是表B中的主鍵

這裏的用法我想:

所以
#including 'Person' model for eager loading, this is crucial for me 
c = Couple.find(:all, :include => :persons)[0] 
puts "#{c.first_person.name} and #{c.second_person.name}" 

我怎麼能這樣做呢?

+0

如果你使用Rails,在Person模型的主鍵,爲什麼會是「爲person_id 「而不僅僅是」身份證「? – tfwright 2010-01-24 02:44:39

+0

我改變了這個職位的模特名字,因爲我想把名字保留在互聯網上。它應該是'身份證',但這不是一個困難的解決辦法。只需使用'set_primary_key'。 – user94154 2010-01-24 03:21:37

回答

13

Couple聲明應該是這樣的關係:

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 ...>> 

那些在Person取決於Person是否可以超過一個Couple的一部分。如果Person只能屬於一個Couple,並不能成爲「第一」 Person一個和另一個Second,你可能想:

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 

如果Person可以屬於多個Couple秒,有沒有辦法知道他們是否是「第一」或「第二」,在任何給定的Couple,你可能想:

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 
+0

這是一個寫得很好,經過深思熟慮的答案。非常感謝。我會盡快測試,並讓你知道。 – user94154 2010-01-26 01:54:29

+0

還沒有測試過,但你贏了:) – user94154 2010-01-28 20:40:33

+0

我剛剛使用AREL做了這樣的事情: 'def widgets; Widget.where( Wiget.arel_table [:asset1_id] .EQ(ID)。或者( Widget.arel_table [:asset2_id] .EQ(ID) ) ); end' – thekingoftruth 2015-03-07 01:22:37

0

未經檢驗的,但根據Rails API documentation,也許是這樣的:

class Couple < ActiveRecord::Base 
    has_one :person, :foreign_key => :first_person_id 
    has_one :person, :foreign_key => :second_person_id 
end 
+0

這些應該是belongs_to,而不是has_one,因爲外鍵在這個模型上。 – tfwright 2010-01-24 02:45:24

0

理論而已,未經測試:

創建人的兩個子類:各

class FirstPerson < Person 
    belongs_to :couple 

class SecondPerson < Person 
    belongs_to :couple 

情侶類的has_many :

class Couple 
    has_many :first_persons, :foreign_key => :first_person_id 
    has_many :second_persons, :foreign_key => :second_person_id 

然後找到

Couple.all(:include => [:first_persons, :second_persons]) 
+0

不應該有夫婦'has_one:first_person'和':second_person'? – user94154 2010-01-24 19:46:52

相關問題