I have a nested form that handles a survey and its answers. But I'm getting a strange error when I load the form:
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly
Any ideas? I'm not sure how I should be fixing the associations.
<%= form_for @survey do |f| %>
...
<%= f.fields_for :answers do |builder| %>
<%= builder.text_field :content, :class=>"form-control" %>
<% end %>
...
<% end %>
Survey#new
def new
@survey = Survey.new
@template = Template.find(params[:template_id])
@patient = Patient.find(params[:patient_id])
@survey.answers.build
end
Survey.rb
class Survey < ActiveRecord::Base
belongs_to :template
has_many :questions, :through=> :template
has_many :answers, :through=> :questions
accepts_nested_attributes_for :answers
end
Template.rb
class Template < ActiveRecord::Base
belongs_to :survey
has_many :questions
end
Question.rb
class Question < ActiveRecord::Base
belongs_to :template
has_many :answers
end
Answer.rb
class Answer < ActiveRecord::Base
belongs_to :question
end
You've missed the line has_many :templates
in the Survey.rb.
Also you must specify :templates
(plural of the model name) in the
same file:
has_many :questions, :through=> :templates
So final variant is:
class Survey < ActiveRecord::Base
has_many :templates
has_many :questions, :through=> :templates
has_many :answers, :through=> :questions
accepts_nested_attributes_for :answers
end
Also as your models survey
and answer
are associated, you don't need to get templates in controller:
def new
@survey = Survey.new
@patient = Patient.find(params[:patient_id])
@survey.answers.build
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With