Reputation: 12570
I am trying to run through a simple nested_attributes exercise, where a question has many answers (how like life is that?). I can't get the answers field to show up in either the 'new' or the 'edit' actions. As far as I can tell, I'm following the specs precisely. Clearly, this is not the case. Any pointers appreciated, thanks.
Models
# question.rb
has_many :answers
accepts_nested_attributes_for :answers
# answer.rb
belongs_to :question
View
# _form.html.erb
<%= form_for(@question) do |f| %>
...
<div class="field">
<%= f.label :content, 'Question' %><br>
<%= f.text_field :content %>
</div>
<div class="field">
<% f.fields_for :answers do |ff| %>
<%= ff.label :content, 'Answer' %><br>
<%= ff.text_field :content %>
<% end %>
</div>
...
<% end %>
Controller
# questions_controller.rb
def new
@question = Question.new
@question.answers.build
end
def edit
end
def create
@question = Question.new(question_params)
respond_to do |format|
if @question.save
format.html { redirect_to @question, notice: 'Question was successfully created.' }
format.json { render :show, status: :created, location: @question }
else
format.html { render :new }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
private
def question_params
params.require(:question).permit(:content, answer_attributes: [:id, :content, :question_id] )
end
Upvotes: 0
Views: 732
Reputation: 33542
Now I just need to figure out why the nested attribute (the answer) isn't saving to the database.
Extending @Dylan Markow's answer.
Since it is has_many answers
,it should be answers_attributes
instead of answer_attributes
in your question_params
method.
def question_params
params.require(:question).permit(:content, answers_attributes: [:id, :content, :question_id] )
end
Upvotes: 1
Reputation: 124469
Use <%=
, not <%
, otherwise the resulting output from the field_for
Form Builder won't be output to the form.
<%= f.fields_for :answers do |ff| %>
Upvotes: 2