2014-03-27 30 views
0

保存has_many上的額外字段我通過關聯實際上有一個has_many,以便從用戶表中鏈接父項和子項。 因此,這裏是我有我的模型:Rails:如何通過

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 [:user] [:relation])。

所以我試圖做的事:

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

感謝您的回答。是的,我意識到我需要設置'accepted_nested_attributes_for'。然而,我仍然有一個問題,因爲我根本不知道如何將這些數據附加到我的'resource.childrens'上。想法? – lkartono

+0

如何使用強參數? – Pavan

+0

well我已經允許'[:relation]'params通過:'u.permit(:relation)' – lkartono