无法使用嵌套属性批量分配受保护的属性

时间:2013-07-26 14:20:16

标签: ruby-on-rails

之前我使用过嵌套属性和form_for,但我只是遗漏了一些简单的东西。这是我的模特......

skill.rb

class Skill < ActiveRecord::Base
  belongs_to :tag
  attr_accessible :tag_id, :user_id, :weight
end

tag.rb

class Tag < ActiveRecord::Base
  has_many :skills
  attr_accessible :name, :skills_attributes
  accepts_nested_attributes_for :skills
end

的应用程序/视图/标签/ _form.html.erb

 <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <%= f.fields_for :skill do |s| %>
    <%= s.label :weight %><br />
    <%= s.text_field :weight %>
  <% end %>

两个模型的parms正在通过,但是我在控制台中收到了一个质量分配错误...

Started POST "/tags" for 127.0.0.1 at 2013-07-26 10:13:51 -0400
Processing by TagsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"yofQhmgOyNHvnws/Lg+BoS4TqeTwPdyQjQbLXotnEzI=", "tag"=>{"name"=>"test", "skill"=>{"weight"=>"ee"}}, "commit"=>"Create Tag"}
Completed 500 Internal Server Error in 1ms

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: skill):
  app/controllers/tags_controller.rb:43:in `new'
  app/controllers/tags_controller.rb:43:in `create'

任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:1)

在tag.rb中,使技能属性可访问。

class Tag < ActiveRecord::Base
  has_many :skills
  attr_accessible :name, :skills_attributes, :skill
  accepts_nested_attributes_for :skills
end

答案 1 :(得分:1)

您可以尝试以下方法来处理has_many:

    <% @tag.skills.each do |skill| %>
        <%= f.fields_for :skills, skill do |s| %>
            <%= s.label :weight %><br />
            <%= s.text_field :weight %>
        <% end %>
    <% end %>

在控制器new / edit中:

    @tag.skills.build if @tag.skills.empty?

答案 2 :(得分:1)

Jeremy Pinnix上面的回答是正确的,只需要更改您的查看代码:

 <%= f.fields_for :skills do |s| %>
   <%= s.label :weight %><br />
   <%= s.text_field :weight %>
 <% end %>

您应该以复数形式引用您的fields_for关联。即技能不是技能。