0

我有三个模型。父、子、类型和关系。关系是引用父、子和类型的富连接模型。

问题是,虽然创建了一个孩子并创建了关系表,但没有填充关系表中的 parent_id。只有子项和类型是自动填充的。

父.rb

attr_acccessible :relationships_attributes

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

子.rb

attr_acccessible :relationships_attributes

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

accepts_nested_attributes_for :relationships

关系.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

新的.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 %>

请帮忙。

谢谢!

4

1 回答 1

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
于 2012-10-16T10:09:11.843 回答