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
<%= 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'
我其實早些時候嘗試過,它打破了窗體。以下是錯誤: **練習中的參數錯誤#new 找不到名爲'exercise'的關聯。它是否已被定義?** – phillipmaddox 2013-04-06 02:47:28
您在說您接受':exercises'的嵌套屬性,但您尚未定義它。爲什麼你在'Tag'上有'accep_nested_attributes_for:exercises'這行? – 2013-04-06 02:58:30
我猜它在Tag模型中是一個錯誤,但我認爲它已經在練習模型中定義了嗎? *我添加了一個exercise_id:整數字段到標籤表FYI。但仍然有同樣的問題。 – phillipmaddox 2013-04-06 04:13:51