1

親オブジェクトの更新時に関連付けを更新するフォームを作成しようとしています。accepts_nested_attributes_forオプションも使用しようとしましたattr_accessibleが、まだCan't mass-assign protected attributesエラーが発生しています。

ここに私のモデルがあります:

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 %>

私のフォームは、複数の Effect レコードを含む Mastery レコード用です。このエラーが発生する理由と、それを修正するために何ができるか、誰にもわかりますか?

4

1 に答える 1

1

私は2つのことをすることでこれを解決しました:

1) 使用するフォーム構造を変更しfields_for

2) :effects_attributesMastery モデルの 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
于 2013-02-06T17:28:59.700 に答える