2013-09-11 3 views
0

나는 관련이 있습니다연결에 추가 속성을 추가하려면 어떻게합니까?

그것은 다른 부모 부모를 만들고 연결하는 작업
class ParentChild < ActiveRecord::Base 
    attr_accessible :parent_id, child_id, position 

    belongs_to class2, :foreign_key => "child_id" 
end 


class Parent< ActiveRecord::Base 

    has_many parent_child 
    has_many Parent, through: :parent_child 
end 

:

Parent.create.parents << Parent.create 

을하지만이 경우, 추가 속성을 설정하는 것이 가능 내의 위치 속성입니다 학부모 자녀 모델? 이 같은

뭔가 :

parent.parents << Parent.create, 3 

답변

0

당신은 당신이 쓴대로 작동하게하려면, 당신은 관계 확장을 사용해야합니다

has_many :parents, :through => :parent_child do 
    def << (parent_object, position) 
    proxy_association.owner.parent_child.create(:child_id => parent_object.id, :position => position) 
    end 

    alias :add, :<< 
end 
+0

고마워, thats perfect 내가 찾고 있는게 뭐니? – Rene

0

당신은 직접 ParentChild 기록을 만들 수 있습니다

grand_parent = Parent.create 

relationship = ParentChild.create(
       parent_id: grand_parent.id, 
       child_id: parent.id, 
       position: 3 
       )