我有三个型号。父,子,类型和关系。 Relationship是引用Parent,Child和Type的富连接模型。
问题在于创建子节点并创建关系表时,不会填充关系表中的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 %>
请帮忙。
谢谢!
答案 0 :(得分: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