嵌套模型表单:一个子类不保存其更改

时间:2011-09-29 18:02:00

标签: ruby-on-rails

我正在使用嵌套模型表单,该表单似乎与浏览器体验有关。但是,当我提交表单时,只有一个子类可以正确更新。

以下是模型:

用户:

class User < ActiveRecord::Base
  has_many :ducks
  has_many :places
  accepts_nested_attributes_for :ducks, :places
  ...
end

鸭:

class Duck < ActiveRecord::Base
  belongs_to :user
    attr_accessible :name, :selected
  ...
end

地点:

class Place < ActiveRecord::Base
  belongs_to :user
    attr_accessible :name, :address
end

形式:

<%= form_for(@user) do |user_form| %>
  <div class="field">
    <%= user_form.label :first_name %><br />
    <%= user_form.text_field :first_name %>
  </div>
  .
  .
  .
  <% user_form.fields_for :ducks do |duck_form| %>
    <%= duck_form.label duck_form.object.name %>
    <% unless duck_form.object.new_record? %>
      <%= duck_form.check_box 'selected?' %>
      <%= duck_form.label 'selected?', 'Enabled' %>
      <br />
    <% end %>
  <% end %>

  <% user_form.fields_for :places do |place_form| %>
    <%= place_form.label place_form.object.name %>
        <%= place_form.text_field :address %>
        <br />
  <% end %>

  <div class="actions">
    <%= user_form.submit "Update" %>
  </div>
<% end %>

当我提交表单时,会更新用户数据(父类),并正确选择/取消选择鸭子(子类1),但地点(子类2)保留其先前值。

为什么Place字段没有更新?


修改:更新了问题以反映从aliasplace的迁移,感谢rdvdijk的评论。不幸的是,这并没有解决问题。


编辑2:这是我日志文件中的相关位。

Started POST "/users/1" for 127.0.0.1 at 2011-09-29 14:57:27 -0700
  Processing by UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"CILQ3U47rQtR9kJZ6ToAfJ7fgwqCRnrMALDZxELmFQg=", "user"=>{"first_name"=>"Foo", "last_name"=>"Man", "email"=>"foo@man.co", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "ducks_attributes"=>{"0"=>{"selected"=>"1", "id"=>"1"}, "1"=>{"selected"=>"1", "id"=>"2"}}, "places_attributes"=>{"0"=>{"address"=>"werwerwerwe", "id"=>"1"}, "1"=>{"address"=>"oiwneroinwer", "id"=>"2"}}}, "commit"=>"Update", "id"=>"1"}
  User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
WARNING: Can't mass-assign protected attributes: places_attributes

显然最后一行是问题所在。但即使将attr_accessible扩展为包含所有Place的字段(:name, :address, :id, :user_id, :created_at, :updated_at)也无法解决问题。

2 个答案:

答案 0 :(得分:1)

alias是Ruby中的保留关键字。重命名模型,然后重试。

答案 1 :(得分:0)

事实证明我的places未被列为attr-accessible,遗憾的是我没有在原始问题中包含这些内容:

attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
                :ducks_attributes

添加:places_attributes解决了问题:

attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
                :ducks_attributes, :places_attributes

希望这有助于某人避免同样的问题;我在原始问题中遗漏了这一点道歉。