嵌套模型上的Noob問題。Rails 4 - 嵌套模型(2級)不保存
我用Rails 4,並試圖建立嵌套模型如下:
調查,有許多問題 每個問題有很多答案
我下面Rails Casts episode #196創建的一個調查,問題和答案同樣的形式。 Surevey和Realted問題得到保存,但答案沒有保存到數據庫(答案字段顯示正確)。
我真的很感激您對此的意見。
謝謝, 邁克
surveys_controller.rb
def index
@surveys = Survey.all
end
def new
@survey = Survey.new
3.times do
question = @survey.questions.build
1.times { question.answers.build }
end
end
def create
@survey = Survey.new(survey_params)
respond_to do |format|
if @survey.save
format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
format.json { render action: 'show', status: :created, location: @survey }
else
format.html { render action: 'new' }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
def survey_params
params.require(:survey).permit(:name,questions_attributes:[:content,answer_attributes:[:content]])
end
new.html.erb
<h1>New survey</h1>
<%= render 'form' %>
<%= link_to 'Back', surveys_path %>
_form.html.erb:
<%= 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>
<!--Display Questions -->
<%= f.fields_for :questions do |builder| %>
<%= render 'question_fields', :f => builder%>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
_questions_fields.html.erb:
<p>
<%= f.label :content, "Question" %><br />
<%= f.text_area :content, :rows => 3 %>
</p>
<!--Display Answers -->
<%=f.fields_for :answers do |builder| %>
<p>
<%= render 'answer_fields', :f => builder%>
</p>
<%end%>
_answers_fields.html.erb:
<p>
<%= f.label :content, "Answer" %>
<%= f.text_field :content%>
</p>
調查型號:
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
end
問題型號:
class Question < ActiveRecord::Base
belongs_to :survey
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers
end
答型號:
class Answer < ActiveRecord::Base
belongs_to :question
end
我在閱讀時注意到的一件事是您使用'1.times {blah}',但您不應該這樣做,因爲默認情況下,普通代碼行運行1次 –