我的accep_nested_attributes_for仅保存父项而不保存子项(嵌套)属性。这是父母与孩子之间的许多关系。accep_nested_attributes_for未将子属性保存到数据库
问题:什么也没有发生,也没有保存。但是在页面上,我得到这个消息:
utf8: "\xE2\x9C\x93"
authenticity_token: 9Pjxt7e5RRgWVGafRyMoDqBSqmtj/R2zBSiVxGGxFOI=
parent: !map:ActiveSupport::HashWithIndifferentAccess
name: "Test"
gender: Male
children_attributes: !map:ActiveSupport::HashWithIndifferentAccess
"0": !map:ActiveSupport::HashWithIndifferentAccess
email: [email protected]
commit: Submit
从味精在我的终端的日志,我认为这是因为children_attributes从来没有得到保存为它分配一个“0”?这是终端MSG:
Started POST "/parents" for 127.0.0.1 at 2011-09-14 11:14:14 -0400
Processing by ParentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9Pjxt7e5RRgWVGafRyMoDqBSqmtj/R2zBSiVxGGxFOI=", "parent"=>{"name"=>"123", "gender"=>"Male", "children_attributes"=>{"0"=>{"email"=>"[email protected]"}}}, "commit"=>"Submit"}
SQL (0.1ms) BEGIN
SQL (0.6ms) SELECT 1 FROM `children` WHERE (LOWER(`children`.`email`) = LOWER('[email protected]')) LIMIT 1
SQL (0.2ms) ROLLBACK
控制器 -
def new
@parent = Parent.new
@parent.children.build
end
def create
@parent = Parent.new(params[:parent])
if @parent.save
redirect_to root_path
else
render 'new'
end
end
父模型 -
attr_accessible :children_attributes
has_many :children, :through => :parent_child_relationships
accepts_nested_attributes_for :children
儿童模型 -
has_many :parents, :through => :parent_child_relationships
validates :email, :name, :presence => true
父形式视图 -
<%= form_for(@parent, new_parent_path) do |f| %>
<div>
<%= f.label(:name) %></br>
<%= f.text_field(:name) %>
</div>
<div>
<%= f.label(:gender) %> <br/>
<%= f.select(:gender, ['Male', 'Female']) %>
</div>
<%= f.fields_for :children do |ff| %>
<div>
<%= ff.label(:email)%></br>
<%= ff.text_field(:email)%>
</div>
<% end %>
<%= submit_tag "Submit" %>
<% end %>
任何帮助将不胜感激!谢谢!
就是这样。我有一些验证,当用户自己创建一个孩子(而不是通过嵌套关联)。有没有一种方法可以使这些验证仅在创建子本身时有效,并且在它是嵌套属性的一部分时忽略这些验证?谢谢 – noob
上面编辑了我的回复。 –
我认为通过使用新的代码@ parent.children.build,您是否有效地创建了新的子对象?我有我的孩子模型中的其他validates_presence,所以即使我这样做,:on => create,是否仍然不会通过验证?我现在清理了我的验证,所以这仅仅是为了我自己的知识。 – noob