我无法保存嵌套窗体中的两个字段。父字段可以很好地保存,但嵌套字段会抛出“警告:无法批量分配受保护的属性”错误。Rails 3.0.5嵌套窗体 - 无法创建新 - 警告:无法批量分配受保护的属性
我用attr_accessible把东西放在Item模型中,但它没有解决问题。
List_controller
def create
@list = List.new(params[:list])
@list[:user_id] = current_user.id
if @list.save
flash[:notice] = "Successfully created list."
redirect_to @list
else
render :action => 'new'
end
end
列表模型
class List < ActiveRecord::Base
has_many :items, :dependent => :destroy
accepts_nested_attributes_for :items, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end
项目模型
class Item < ActiveRecord::Base
belongs_to :list
end
形式
<%= form_for(@list) do |list_form| %>
<p>
<%= list_form.label :title %><br />
<%= list_form.text_field :title %>
</p>
<p>
<%= render :partial => 'item_fields',
:locals => {:form => list_form} %>
</p>
<%= list_form.submit %>
<% end %>
表格部分
<%= form.fields_for :item do |item_form| %>
<%= item_form.label :name, 'item' %>
<%= item_form.text_field :name %>
<% end %>
Server错误日志
Started POST "/lists" for 127.0.0.1 at Sun Mar 27 02:54:18 -0400 2011
Processing by ListsController#create as HTML
Parameters: {"commit"=>"Create List", "list"=>{"title"=>"figaro", "item"=>{"na
me"=>"foobar"}}, "authenticity_token"=>"afu5xPgvJenu6XKXcsyilR8RconLP/OZ3NxsICE3RVk=
", "utf8"=>"Γ£ô"}
←[1m←[35mUser Load (1.0ms)←[0m SELECT "users".* FROM "users" WHERE "users"."i
d" = 2 LIMIT 1
WARNING: Can't mass-assign protected attributes: item
←[1m←[36mAREL (2.0ms)←[0m ←[1mINSERT INTO "lists" ("user_id", "updated_at", "
title", "created_at") VALUES (2, '2011-03-27 06:54:18.893302', 'figaro', '2011-0
3-27 06:54:18.893302')←[0m
Redirected to http://localhost:3000/lists/77
Completed 302 Found in 117ms
谢谢,我一直试图在Item模型中添加变体,但我应该将它添加到List模型中 – xta 2011-03-28 04:54:44