在构建嵌套属性表单时无法批量分配受保护的属性::问题

时间:2013-04-06 02:25:51

标签: ruby-on-rails nested-forms foreign-key-relationship nested-attributes mass-assignment

我几乎整天都花在这个特定的问题上,虽然还有其他帖子,但我没有解决我的特定问题。

我已尝试关注RailsCast #196,但仍然无法识别我的错误。

模型:

锻炼

# == Schema Information
#
# Table name: exercises
#
#  id          :integer          not null, primary key
#  name        :string(255)
#  description :text
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#  image       :string(255)
#

class Exercise < ActiveRecord::Base
  attr_accessible :description, :name, :tags_attributes
  has_many :tags
  has_one :difficulty
  accepts_nested_attributes_for :tags, :allow_destroy => true
end

代码

# == Schema Information
#
# Table name: tags
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Tag < ActiveRecord::Base
  attr_accessible :name, :exercise_id
  belongs_to :exercise
  accepts_nested_attributes_for :exercises
end

FORM

<%= form_for(@exercise) do |f| %>
  <% if @exercise.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@exercise.errors.count, "error") %> prohibited this exercise from being saved:</h2>

      <ul>
      <% @exercise.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <%= f.fields_for :tag do |builder| %>
    <div class="field">
        <%= builder.label :name, "Tags" %><br />
        <%= builder.text_field :name %>     
    </div>
<% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

错误,特别是我提交表单时的错误是:

ActiveModel::MassAssignmentSecurity::Error in ExercisesController#create

Can't mass-assign protected attributes: tag

Application Trace | Framework Trace | Full Trace
app/controllers/exercises_controller.rb:42:in `new'
app/controllers/exercises_controller.rb:42:in `create'

1 个答案:

答案 0 :(得分:1)

在表单中,替换

<%= f.fields_for :tag do |builder| %>

<%= f.fields_for :tags do |builder| %>

在您的模型中,您使用attr_accessible,然后添加复数,然后添加_attributes,以便您可以设置属性,但在您的表单中,您调用了单数tag因此为什么你得到一个质量分配受保护的属性错误。