2014-03-27 2 views
0

실제로 사용자 테이블에서 부모와 자식을 연결하기 위해 has_many through association이 있습니다.레일 : has_many에 여분의 필드를 저장하는 방법

class User < ActiveRecord::Base 
    has_many :parents_to_children, class_name: ParentsUser, foreign_key: :children_id 
    has_many :parents, through: :parents_to_children, source: :parent 

    has_many :children_to_parents, class_name: ParentsUser, foreign_key: :parent_id 
    has_many :childrens, through: :children_to_parents, source: :children 
end 

class ParentsUser < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :parent, class_name: User 
    belongs_to :children, class_name: User 
end 

테이블에 가입 제는 다음과 같습니다 :

는 데이터를 저장하기 위해
|----------------------------------------------------| 
| id | children_id | parent_id | relation_type | 
|----------------------------------------------------| 

, 내가하고 있어요 (지금까지 그래서 여기 내가 내 모델에있어 무엇인가) :

resource.childrens << user if user 

이 잘 작동하고 잘하지만, 불행하게도 relation_type이 (저장되지 않습니다 PARAMS [: 사용자] [: 관계]).

그래서 내가 할 시도했다 :

resource.childrens.build(childrens: [user], relation_type: params[:user][:relation]) if user 

을하지만 오류 받고 있어요 : 우아한 방법으로이를 수행하는 방법에 대한 unknown attribute: relation_type

어떤 아이디어?

답변

0

당신은 accepts_nested_attributes_for가 없습니다. 당신의 User 모델이 작성하는 것은

accepts_nested_attributes_for :parents_user 

이 문제를 해결할 수 있습니다.

+0

답변 해 주셔서 감사합니다. 예, accepts_nested_attributes_for를 설정해야한다는 것을 알게되었습니다. 그러나, 나는'resource.childrens'에 그 데이터를 추가하는 방법을 모른다. 아이디어? – lkartono

+0

강력한 매개 변수 사용은 어떻습니까? – Pavan

+0

잘'[: relation]'매개 변수가 통과하도록 허용 :'u.permit (: relation)' – lkartono