【问题标题】:Cannot modify association 'Survey#answers' because it goes through more than one other association无法修改关联“Survey#answers”,因为它通过多个其他关联
【发布时间】:2015-05-23 22:36:09
【问题描述】:

我有一个处理调查及其答案的嵌套表单。但是我在加载表单时遇到了一个奇怪的错误:

ActiveRecord::HasManyThroughNestedAssociationsAreReadonly

有什么想法吗?我不确定我应该如何修复这些关联。

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

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

...

<% end %>

调查#新

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

调查.rb

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

模板.rb

class Template < ActiveRecord::Base
    belongs_to :survey
    has_many :questions
end

问题.rb

class Question < ActiveRecord::Base
  belongs_to :template
  has_many :answers
end

答案.rb

class Answer < ActiveRecord::Base
  belongs_to :question
end

【问题讨论】:

  • 嗨!我遇到了类似的问题,你有没有找到一个可行的解决方案?

标签: ruby-on-rails forms nested


【解决方案1】:

您错过了 Survey.rb 中的 has_many :templates 行。 此外,您还必须在 同一个文件:

has_many :questions, :through=&gt; :templates

所以最终的变体是:

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

由于你的模型surveyanswer 是关联的,你不需要在控制器中获取模板:

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

【讨论】:

  • 嗯......不幸的是,这仍然没有解决错误。
猜你喜欢
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多