我正在使用cocoon gem来嵌套表单。我的rails版本是4.2.6。
两个模型之间的关联设置如下
Question.rb
class Question
include Mongoid::Document
field :title, type: String
has_many :choice_options, dependent: :destroy
accepts_nested_attributes_for :choice_options, :reject_if => :all_blank, :allow_destroy => true
validates :topic, presence: true
end
ChoiceOption.rb
class ChoiceOption
include Mongoid::Document
field :title, type: String
belongs_to :question
end
我在问题控制器
中设置new
和question_params
如下
questions_controller.rb
class QuestionsController < ApplicationController
def new
@question = Question.new
end
private
def question_params
params.require(:question).permit(:title, choice_options_attributes: [:id, :title, :_destroy])
end
end
创建新问题和嵌套选择的部分表单如下。
视图/问题/ _form.html.erb
<%= form_for @question do |f| %>
<%= render 'shared/errors', object: @question %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_area :title, rows: 3, required: true, class: 'form-control' %>
</div>
<div class="panel panel-default">
<div class="panel-heading">Options</div>
<div class="panel-body">
<%= f.fields_for :choice_options do |options_form| %>
<%= render 'choice_option_fields', f: options_form %>
<% end %>
<div class="links">
<%= link_to_add_association 'add option', f, :choice_options %>
</div>
</div>
</div>
<%= f.submit 'Create', class: 'btn btn-primary btn-lg' %>
<% end %>
然后我创建了一个部分表单供我在上一页中呈现的选项。
视图/问题/ _choice_option_fields.html.erb
<div class="nested-fields">
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control', required: true %>
</div>
<%= link_to_remove_association "remove option", f %>
</div>
现在,当我尝试点击部分表单中的添加选项链接时,它不会显示。网址以
结尾 http://localhost:3000/questions/new#
答案 0 :(得分:1)
您忘了在新的
中启动选择选项class QuestionsController < ApplicationController
def new
@question = Question.new
@question.choice_options.build
end
end