Reputation: 1425
I am using cocoon gem for nested forms. My rails version is 4.2.6.
The association set between two models is as follows
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
And I have new
and question_params
set as follows in questions controller
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
The partial form to create a new question and nested choice is as follows.
views/questions/_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 %>
And then I have created a partial form for choices which I am rendering in the above page.
views/questions/_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>
Now when I am trying to click the add option link from the partial form, its not appearing. the url is ending at
http://localhost:3000/questions/new#
Upvotes: 0
Views: 41
Reputation: 2541
You forgot to initiate the choice options in new
class QuestionsController < ApplicationController
def new
@question = Question.new
@question.choice_options.build
end
end
Upvotes: 1