Не удается массово назначить защищенные атрибуты:: проблема при создании вложенной формы атрибута
Я потратил почти весь день на эту конкретную проблему, и хотя есть и другие сообщения об этом, я не решил свою конкретную проблему.
Я пытался следовать 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 ответ
В вашей форме замените строку
<%= f.fields_for :tag do |builder| %>
с
<%= f.fields_for :tags do |builder| %>
В вашей модели вы используете attr_accessible
а затем вы добавляете множественное число с последующим _attributes
так что вы можете установить атрибуты, но в вашей форме вы назвали единственное число tag
следовательно, почему вы получаете ошибку массового назначения защищенных атрибутов.