F.fields_for has_many relationships in rails
I have a scoring model that has multiple answers. I am trying to create my f.fields_for, but I get the error:
"undefined method `content' for <Answer::ActiveRecord_Associations_CollectionProxy:0x007fdb12041fd8>"
View:
<%= f.fields_for @answers do |builder| %>
<%= builder.text_area :content, :class=>"form-control question-field", :data => {:question => question.id} %>
<% end %>
Controller:
def edit
@assessment = current_user.assessments.find(params[:id])
@answers = @assessment.answers
end
I understand that the error is that I am calling the methods on the collection and not on a separate object. But I don't understand how to fix this.
source to share
If f
is a builder for @assassment
, you can do:
<%= f.fields_for :answers do |builder| %>
<%= builder.text_area :content, :class=>"form-control question-field", :data => {:question => question.id} %>
<% end %>
You will also need this in your model Assassement
:
class Assasement < ActiveRecord::Base
has_many :answers
accepts_nested_attributes_for :answers
#...
end
source to share
#fields_for
expects object_name
as first parameter or object
- but not a collection. So you have two options, depending on the context. Or get the child collection from the outher ( f
) form helper implicitly:
<%= f.fields_for :answers do |builder| %>
Or pass a specific collection as the second argument, for example:
<%= f.fields_for :answers, @answers do |builder| %>
Specifications: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
source to share