我有DayItem模型,它有一个SchoolProgram,有许多研讨会。
class DayItem < ActiveRecord::Base
has_one :school_program, dependent: :destroy
has_many :seminars, through: :school_program
accepts_nested_attributes_for :school_program
accepts_nested_attributes_for :seminars, reject_if: :all_blank
end
class SchoolProgram < ActiveRecord::Base
belongs_to :day_item
has_many :seminars, dependent: :destroy
accepts_nested_attributes_for :seminars, allow_destroy: true, reject_if: :all_blank
end
class Seminar < ActiveRecord::Base
belongs_to :school_program
end
我正在使用cocoon gem作为动态嵌套表单,如下所示。
_form.html.haml:
= simple_form_for [@day, @day_item] do |f|
= f.input :start_time
= f.simple_fields_for :school_program do |form|
= form.input :school
= form.simple_fields_for :seminars do |seminar|
= render 'seminar_fields', :f => seminar, :parent => form
.links
= link_to_add_association 'add seminar', form, :seminars
_seminar_fields.html.haml:
.nested-fields.well.well-compact
.form-inline
= f.input :name
= link_to_remove_association "remove seminar", f
但是当我尝试添加研讨会时,我会遇到异常。
ActiveEcord :: HasManyThroughCantAssociateThroughHasOneOrManyReflection在Etm :: DayItemsController#update
无法修改关联'DayItem#seminars',因为源反射类'Seminar'通过以下方式与'SchoolProgram'相关联:has_many。
感谢任何帮助。
答案 0 :(得分:1)
这里可能存在多个问题,但第一个应该解决的问题是您与研讨会的关系会创建一个循环引用。它在DayItem中的has_many中声明,然后在SchoolProgram上声明为has_one,它本身属于父类DayItem。请尝试以下更改我们的DayItem模型。保留其他型号,让我知道它是怎么回事。
class DayItem < ActiveRecord::Base
has_one :school_program, dependent: :destroy
accepts_nested_attributes_for :school_program
end