2012-07-19 94 views
0

我有三個模型。父母,孩子,類型和關係。關係是引用Parent,Child和Type的豐富連接模型。欄目嵌套屬性has_many到

問題是,當創建子對象並創建關係表時,關係表中的parent_id未填充。只有孩子和類型是自動填充的。

parent.rb

attr_acccessible :relationships_attributes 

has_many :relationships 
has_many :children, :through => :relationships 
has_many :types, :through => :relationships 

child.rb

attr_acccessible :relationships_attributes 

has_many :relationships 
has_many :parents, :through => :relationships 
has_many :types, :through => :relationships 

accepts_nested_attributes_for :relationships 

relationship.rb

attr_accessible :parent_id, :child_id, :type_id 
belongs_to :parent 
belongs_to :child 
belongs_to :type 

children.controller

def new 
@child = Child.new 
@child.relationships.build 
end 

def create 
@child = Child.new(params[:child]) 
if @child.save 
    redirect_to current_user 
else 
    render "new" 
end 
end 

new.html.erb

<%= simple_form_for @child do |f| %> 
    <%= f.input :first_name, :label => 'First Name' %> 
    <%= f.input :gender, :as => :select, :collection => ['Male', 'Female'] %> 
    <%= f.association :relation_types, :as => :collection_select %> 


    <%= f.button :submit, :class => "primary" %> 

<% end %> 

請幫忙。

謝謝!

回答

2

似乎忘記很多事情:

@child.relationships.build 

應該

@child.relationships.build :parent_id => ... 

,並鑑於 代替

f.association :relation_types, :as => :collection_select 

使用

f.field_for :relationships do |g| 
    g.association :types, :as => :collection_select 
    g.hidden :parent_id #need to save this 
+0

謝謝你。是否有另一種方法來合併父母ID?我寧願不使用隱藏的領域。 – noob 2012-10-19 17:47:29

+0

如果你不希望它在父母身份證,也許你可以隱藏它的參數(改變形式的網址或更改routes.rb使這個資源嵌套(這是不容易的)) – qoyyim 2012-10-30 04:06:57

+0

你也可以使用'@child = @ parent.children。 build' – qoyyim 2015-12-01 07:14:11