2013-02-06 35 views
1

我試圖構建更新父對象時更新關聯的表單。我一直在嘗試使用accepts_nested_attributes_for選項以及attr_accessible,但我仍然遇到Can't mass-assign protected attributes錯誤。使用accept_nested_attributes_for更新關聯的問題

這裏是我的模型:

class Mastery < ActiveRecord::Base 
    attr_accessible :mastery_id, 
        :name, 
        :icon, 
        :max_points, 
        :dependency, 
        :tier, 
        :position, 
        :tree, 
        :description, 
        :effects_attributes 
    has_many :effects, :as => :affects, :dependent => :destroy, :order => 'effects.value' 
    accepts_nested_attributes_for :effects 
end 


class Effect < ActiveRecord::Base 
    attr_accessible :name, 
        :modifier, 
        :value, 
        :affects_id, 
        :affects_type 
    belongs_to :affects, :polymorphic => true 
end 

這裏的那部分的呈現形式:

<%= semantic_form_for [ :manage, resource ], :html => {:class => 'default-manage-form' } do |f| %> 
    <%= f.inputs do %> 
    <% attributes.each do |attr| %> 
     <%= f.input attr.to_sym %> 
    <% end %> 

    <% if resource.respond_to? :effects %> 
     <% resource.effects.each do |effect| %> 
     <hr> 
     <%= f.inputs :modifier, :name, :value, :for => effect %> 
     <% end %> 
    <% end %> 

    <%= f.actions do %> 
     <%= f.action :submit %> 
    <% end %> 
    <% end %> 
<% end %> 

我的形式是一個包含多個效果記錄通達記錄。任何人都可以看到爲什麼我會遇到這個錯誤,我能做些什麼來解決它?

+0

我沒有得到什麼':manage and:resource'意思是在你的'semantic_form_for'中。你可以解釋嗎? – codeit

+0

您是否真的擁有:Mastery模型中的mastery_id或者它只是一個錯字? –

+0

@SybariteManoj我做了,意識到這是一個錯誤,並將其刪除。 – gdavis

回答

1

我已經做兩件事情解決了這個:

1)改變形式結構使用fields_for

2)添加:effects_attributes到attr_accessible的通達模型

這裏是新的表單代碼:

<%= semantic_form_for [ :manage, resource ], :html => {:class => 'default-manage-form' } do |f| %> 
    <%= f.inputs do %> 
    <% attributes.each do |attr| %> 
     <%= f.input attr.to_sym %> 
    <% end %> 

    <% if resource.respond_to? :effects %> 
     <%= f.fields_for :effects do |b| %> 
     <hr> 
     <%= b.inputs :modifier, :name, :value %> 
     <% end %> 
    <% end %> 

    <%= f.actions do %> 
     <%= f.action :submit %> 
    <% end %> 
    <% end %> 
<% end %> 

和成品模型:

class Mastery < ActiveRecord::Base 
    attr_accessible :name, 
        :icon, 
        :max_points, 
        :dependency, 
        :tier, 
        :position, 
        :tree, 
        :description, 
        :effects_attributes 
    has_many :effects, :as => :affects, :dependent => :destroy, :order => 'effects.value' 
    accepts_nested_attributes_for :effects 
end