我正在关注railscasts 196集,我正在尝试他所拥有的,但我有以下错误
ActiveModel::MassAssignmentSecurity::Error in SurveysController#create
Can't mass-assign protected attributes: questions_attributes
Rails.root: /home/jean/rail/surveysays
到目前为止我的代码
调查表
<%= form_for(@survey) do |f| %>
<% if @survey.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
<ul>
<% @survey.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>
<%= f.fields_for :questions do |bf|%>
<%= bf.label :content, "Question" %><br />
<%= bf.text_area :content, :rows=> 3 %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
调查关系
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
attr_accessible :name
end
问题关系
class Question < ActiveRecord::Base
belongs_to :survey
attr_accessible :content, :survey_id
end
新控制器
def new
@survey = Survey.new
3.times {@survey.questions.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: @survey }
end
end
答案 0 :(得分:0)
将您的班级更改为此
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
attr_accessible :name, :questions_attributes
end
查找主题“使用attr_accessible”here了解更多信息