2016-12-08 6 views
0

아래 그림과 같이 Person을 다른 Person의 부모로 지정할 수 있도록 Person Model을 정의 할 수 있습니까? Person의 테이블을 만드는 마이그레이션에서 정의해야하는 열은 무엇입니까? 그래서 아직 시나리오의 경우 작업 belongs_to하지, 내가 대답보다 unserstandRails ActiveRecord. 내가 속한 것을 어떻게 처리 할 수 ​​있습니까?

irb(main):001:0> john = Person.create(name: "John") 
irb(main):002:0> jim = Person.create(name: "Jim", parent: john) 
irb(main):003:0> bob = Person.create(name: "Bob", parent: john) 
irb(main):004:0> john.children.map(&:name) 
=> ["Jim", "Bob"] 

class People < ActiveRecord::Base 
     has_many :children, class_name: "People", foreign_key: "parent_id" 
     belongs_to :parent, class_name: "People" #Question HERE? how to deal with belong_to more than one? 
end 

class AddXXTOXXX <ActiveRecord::Migration 
      def change 
       create_table :peoples do |t| 
        t.add_column :name, string 
        t.add_column :parent, string 
        t.references :parent, index: true 
        t.timestamps 
       end 
      end 
end 

주변에 뭔가하지만 날 모두가 두 부모 (엄마와 아빠)를 가지고 있다는 것입니다 혼동?

+0

이 링크는 도움이 될 것 같습니다. https://heurionconsulting.wordpress.com/2007/05/29/using-belongs_to-to-connect-different-classes/ –

답변

1

아니요, 여러 자녀를 둔 부모가 여러 명인 경우 belongs_to은 적합하지 않습니다.

너는 을 원한다. 너는 무엇이든 그것을 부를 수는 있지만 relationships이 적당하다고 생각한다.

또한 People 클래스를 Person 클래스로 변경하여 레일 규칙을 준수하십시오.

class Person < ActiveRecord::Base 

    has_many :ancestors, class_name: 'Relationship', foreign_key: :child_id 
    has_many :descendants, class_name: 'Relationship', foreign_key: :parent_id 
    has_many :parents, through: :ancestors, class_name: 'Person', foreign_key: :parent_id 
    has_many :children, through: :descendants, class_name: 'Person', foreign_key: :child_id 

end 
당신은 "엄마"또는 "아버지"와 "아들"또는 "딸"... 그에서 더 나은 추론 할 수 있지만으로, 원하는 경우는 '관계'테이블에 추가 정보를 저장할 수 있습니다

그 사람의 섹스가 존재한다면.