accepts_nested_attributes_for不将子属性保存到数据库

时间:2011-09-14 15:24:31

标签: ruby-on-rails ruby-on-rails-3 nested-forms nested-attributes

我的accepts_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: 1234@testing.com
commit: Submit

从终端日志上的消息来看,我认为这是因为children_attributes从未被保存,因为它被分配了“0”?这是终端消息:

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"=>"1234@testing.com"}}}, "commit"=>"Submit"}
SQL (0.1ms)  BEGIN
SQL (0.6ms)  SELECT 1 FROM `children` WHERE (LOWER(`children`.`email`) = LOWER('1234@testing.com')) 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 %>

任何帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:0)

检查子模型是否有任何不成功的验证

您可以使用以下内容

在创建时进行验证
  validates_uniqueness_of  :xxxx, :on => :create

答案 1 :(得分:0)

您可以将子模型的验证更改为:

validates :name, :presence => true
validates :email, :presence => true, :email => true

看看是否能解决这个问题?