Ruby on rails 3 Rails 3嵌套模型
我试图理解如何用rails嵌套模型(活动记录,然后将其应用到我的mongodb项目中) 下面是railscast教程: 但是,当我无法显示表格向调查中添加新问题时,我就被困在了开始阶段 我已经在模型中建立了关系 模型/调查.erb:Ruby on rails 3 Rails 3嵌套模型,ruby-on-rails-3,model,nested,Ruby On Rails 3,Model,Nested,我试图理解如何用rails嵌套模型(活动记录,然后将其应用到我的mongodb项目中) 下面是railscast教程: 但是,当我无法显示表格向调查中添加新问题时,我就被困在了开始阶段 我已经在模型中建立了关系 模型/调查.erb: class Survey < ActiveRecord::Base has_many :questions, :dependent => :destroy accepts_nested_attributes_for :questions v
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
validates_presence_of :name
end
views/survey/_form.html.erb“
禁止保存此调查:
添加新问题
3 %>
但是当我尝试构建嵌套表单时,它不起作用。我没有收到任何错误,但是表单没有显示
我遗漏了什么吗?您应该使用
您没有充分利用示例中的嵌套表单
要使事情干涸,您应该将(@survey)的表单替换为(@survey)的嵌套表单
然后你可以把问题子表单拉到它自己的部分,然后做一个:
f.fields_for :questions # without a block
并将./app/views/questions/_form.html.erb下的问题表单作为(@question)
这样,您就不必在调查表单中重复问题表单的代码
注意:您需要添加“嵌套表单”“Gem到您的Gemfile。以防万一其他人被困在这里,就像我一样,这个问题是call的括号中缺少的“=”:“谢谢。我对最近读到的一些东西感到困惑。控制逻辑不需要,但这是一个gem,或者是rails的一部分?它是一个gem,称为“nested_from”——您需要将它添加到gem文件中
def new
@survey = Survey.new
@survey.questions.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @survey }
end
end
<%= 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>
<h3>Add new question</h3>
<% f.fields_for :questions do |p| %>
<%= p.label :content, "Questions" %><br />
<%= p.text_area :content, :rows => 3 %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= f.fields_for :questions do |p| %>
f.fields_for :questions # without a block