2011-03-27 43 views
0

我無法保存嵌套窗體中的兩個字段。父字段可以很好地保存,但嵌套字段會拋出「警告:無法批量分配受保護的屬性」錯誤。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 

回答

3

您使用fields_for :item但你的List模式has_many :items

試試這個:

<%= form.fields_for :items do |item_form| %> 

如果這沒有幫助嘗試添加attr_accessible :items_attributesList模型。從docs

[..]如果您使用的是attr_protected或attr_accessible,那麼您需要將屬性編寫器添加到允許的列表中。

+0

謝謝,我一直試圖在Item模型中添加變體,但我應該將它添加到List模型中 – xta 2011-03-28 04:54:44

0

attr_accessible :items添加到您的List類。

相關問題