gpt4 book ai didi

ruby-on-rails - 无法修改关联 'Survey#answers',因为它经历了多个其他关联

转载 作者:行者123 更新时间:2023-12-04 12:53:26 28 4
gpt4 key购买 nike

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

ActiveRecord::HasManyThroughNestedAssociationsAreReadonly

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

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

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

...

<% end %>

调查#new
  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

模板文件
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

最佳答案

您错过了线路 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

也作为你的模特 surveyanswer是关联的,您不需要在 Controller 中获取模板:
def new
@survey = Survey.new
@patient = Patient.find(params[:patient_id])
@survey.answers.build
end

关于ruby-on-rails - 无法修改关联 'Survey#answers',因为它经历了多个其他关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418237/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com