Ruby on rails 嵌套模型形式:一个子类isn';不要保存它的更改
我正在使用一个嵌套的模型表单,它似乎是从浏览器体验中工作的。然而,当我提交表单时,只有一个子类得到了正确的更新 以下是模型: 用户:Ruby on rails 嵌套模型形式:一个子类isn';不要保存它的更改,ruby-on-rails,Ruby On Rails,我正在使用一个嵌套的模型表单,它似乎是从浏览器体验中工作的。然而,当我提交表单时,只有一个子类得到了正确的更新 以下是模型: 用户: 显然,最后一行是问题所在。但是,即使扩展attr\u accessible以包括所有Place的字段(:name、:address、:id、:user\u id、:created\u at、:updated\u at),也不能解决问题。别名在Ruby中是一个保留关键字。重命名您的模型并重试。结果发现我的位置未列为attr accessible,不幸的是,我的原始问
显然,最后一行是问题所在。但是,即使扩展
attr\u accessible
以包括所有Place的字段(:name、:address、:id、:user\u id、:created\u at、:updated\u at
),也不能解决问题。别名在Ruby中是一个保留关键字。重命名您的模型并重试。结果发现我的位置未列为attr accessible
,不幸的是,我的原始问题中没有包括以下几行:
attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
:ducks_attributes
添加:places\u属性修复了该问题:
attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
:ducks_attributes, :places_attributes
希望这能帮助别人避免同样的问题;很抱歉在我的原始问题中遗漏了这一点。不确定是什么问题,但别名在Ruby中是一个保留关键字。你能试着重新命名这个模型看看是否有冲突吗。迁移,谢谢你的捕获!我将提交我的评论作为正确答案,以便您接受。您能显示日志文件中显示已发布变量的部分吗?如果您将ducks
关联移除,只在模型和表单中使用places
,会发生什么情况?不幸的是,这并没有解决它。我相信你在路上帮我省去了一些悲伤!
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 %>
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_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
:ducks_attributes
attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,
:ducks_attributes, :places_attributes