It is not possible to change the "survey responses" association because it goes through several other associations

I have a nested form that processes the survey and its responses. But I get a strange error when loading the form:

ActiveRecord :: HasManyThroughNestedAssociationsAreReadonly

Any ideas? I am not sure how I should establish associations.

<%= form_for @survey do |f| %>

...
<%= f.fields_for :answers do |builder| %>
  <%= builder.text_field :content, :class=>"form-control" %>
<% end %>

...

<% end %>

Review # 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
+4
source share
1 answer

You missed a line has_many :templatesin Survey.rb. You should also specify :templates(the plural of the model name) in the same file:

has_many :questions, :through=> :templates

Thus, the final version:

class Survey < ActiveRecord::Base
      has_many :templates
      has_many :questions, :through=> :templates
      has_many :answers, :through=> :questions
      accepts_nested_attributes_for :answers
    end

, survey answer , :

def new
    @survey = Survey.new
    @patient = Patient.find(params[:patient_id])
    @survey.answers.build
end
+1

All Articles