【发布时间】:2014-01-13 04:14:26
【问题描述】:
关于嵌套模型的菜鸟问题。
我正在使用 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 次
标签: ruby-on-rails ruby-on-rails-4 nested-attributes