Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot modify association 'Survey#answers' because it goes through more than one other association

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
like image 604
Jackson Cunningham Avatar asked May 23 '15 22:05

Jackson Cunningham


1 Answers

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
like image 72
zmii Avatar answered Sep 16 '22 18:09

zmii