2015-07-10 141 views
1

我想在Rails 4中建模一個父母和一些孩子。我試圖建模的關係是每個孩子將有兩個父母,每個父母可以有很多孩子。我已經能夠單親和許多孩子的關係,像這樣的模型:建模父母和孩子在Rails 4

rails g model Parent name:string 
rake db:migrate 
rails g model Child name:string parent_id:integer 
rake db:migrate 

然後我就可以創造像這樣家長:

rails console 
Parent.create(name: 'Joe Bloggs') 

這給了我ID爲1。我父母可以像這樣加入這一個新的子:

Child.create(name: 'Jane Bloggs', parent_id: 1) 

然後我加入的關係模型類child.rb

belongs_to :parent 

所以我現在可以運行:

Child.first.parent 

我如何延長這個讓孩子能有一個母親父母和父親父?

+1

請你展示一些代碼,你嘗試過? – rob

回答

0

爲了回答我自己的問題,我設法讓這個工作。它依靠改變我的孩子模型,使其具有mother_id:integerfather_id:integer。然後添加以下到child.rb

has_one :mother, :class_name => "Parent", :primary_key => "mother_id", :foreign_key => "id" 
has_one :father, :class_name => "Parent", :primary_key => "father_id", :foreign_key => "id" 

,這對當時使我對一個孩子有兩個家長聯繫,並支持以下功能:

Child.first.father 
Child.first.mother 
0

我想你應該在這裏使用has_and_belongs_to_many關聯!請閱讀文檔Rails guides