问题
I am quite new to both programming and ruby on rails. I have followed http://ruby.railstutorial.org/ and then i have started to watch episodes from http://railscasts.com. What i am trying to do is that "Handling multiple models in a single form". Below you will see my models and their assosications and also the view of form that i am trying to get info from users.
My modelling is that;
There are employers, employers have interviews and interviews have questions.
Customquestion model:
class Customquestion < ActiveRecord::Base
attr_accessible :content
belongs_to :interview
validates :content, length: {maximum: 300}
validates :interview_id, presence: true
end
Interview model:
class Interview < ActiveRecord::Base
attr_accessible :title, :welcome_message
belongs_to :employer
has_many :customquestions, dependent: :destroy
accepts_nested_attributes_for :customquestions
validates :title, presence: true, length: { maximum: 150 }
validates :welcome_message, presence: true, length: { maximum: 600 }
validates :employer_id, presence: true
default_scope order: 'interviews.created_at DESC'
end
Form to create new interview;
<%= provide(:title, 'Create a new interview') %>
<h1>Create New Interview</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@interview) do |f| %>
<%= render 'shared/error_messages_interviews' %>
<%= f.label :title, "Tıtle for Interview" %>
<%= f.text_field :title %>
<%= f.label :welcome_message, "Welcome Message for Candidates" %>
<%= f.text_area :welcome_message, rows: 3 %>
<%= f.fields_for :customquestions do |builder| %>
<%= builder.label :content, "Question" %><br />
<%= builder.text_area :content, :rows => 3 %>
<% end %>
<%= f.submit "Create Interview", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
When i fill the form with required information and submit it, i get following error;
Can't mass-assign protected attributes: customquestions_attributes
Application Trace | Framework Trace | Full Trace
app/controllers/interviews_controller.rb:5:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"cJuBNzehDbb5A1Zb14BjBfz1eOsjBCDzGhYKT7q6A0k=",
"interview"=>{"title"=>"",
"welcome_message"=>"",
"customquestions_attributes"=>{"0"=>{"content"=>""}}},
"commit"=>"Create Interview"}
I hope that i have provided enough information for you guys to understand what is problem with that case.
Thank you in advance
回答1:
Just follow what is written in the error message: try to add attr_accessible :customquestions_attributes
to Interview
model:
class Interview < ActiveRecord::Base
attr_accessible :title, :welcome_message, :customquestions_attributes
...
来源:https://stackoverflow.com/questions/10963901/mass-assignment-warning-when-using-nested-attributes