0

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

我试过关注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_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'
4

1 回答 1

1

在您的表单中,替换该行

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

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

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

于 2013-04-06T02:37:04.927 回答