无法修改关联'调查#答案',因为它经历了多个其他关联

Jac*_*ham 7 forms nested ruby-on-rails

我有一个嵌套的表单来处理调查及其答案.但是当我加载表单时,我收到一个奇怪的错误:

的ActiveRecord :: HasManyThroughNestedAssociationsAreReadonly

有任何想法吗?我不确定如何修复这些关联.

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

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

...

<% end %>
Run Code Online (Sandbox Code Playgroud)

调查#新

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

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
Run Code Online (Sandbox Code Playgroud)

Template.rb

class Template < ActiveRecord::Base
    belongs_to :survey
    has_many :questions
end
Run Code Online (Sandbox Code Playgroud)

Question.rb

class Question < ActiveRecord::Base
  belongs_to :template
  has_many :answers
end
Run Code Online (Sandbox Code Playgroud)

Answer.rb

class Answer < ActiveRecord::Base
  belongs_to :question
end
Run Code Online (Sandbox Code Playgroud)

zmi*_*mii 1

has_many :templates您错过了Survey.rb 中的行。此外,您还必须在同一文件中指定:templates(模型名称的复数):

has_many :questions, :through=> :templates

所以最终的变体是:

class Survey < ActiveRecord::Base
      has_many :templates
      has_many :questions, :through=> :templates
      has_many :answers, :through=> :questions
      accepts_nested_attributes_for :answers
    end
Run Code Online (Sandbox Code Playgroud)

此外,当您的模型surveyanswer关联时,您不需要在控制器中获取模板:

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