我有三个型号的应用程序。最高级别是JobSpec
class JobSpec < ActiveRecord::Base
belongs_to :job_template, polymorphic: true, dependent: :destroy, inverse_of: :job_spec
accepts_nested_attributes_for :job_template
end
这与job_template
有多态关联,其中一个是GooddataExtract
模板
class GooddataExtract < ActiveRecord::Base
has_one :job_spec, as: :job_template, inverse_of: :job_template
has_many :gooddata_reports, dependent: :destroy, inverse_of: :gooddata_extract
accepts_nested_attributes_for :gooddata_reports, reject_if: :all_blank, allow_destroy: true
end
反过来与GooddataReport
class GooddataReport < ActiveRecord::Base
belongs_to :gooddata_extract, inverse_of: :gooddata_report
end
我在构造将创建GooddataReport
项的参数哈希时遇到问题。当我使用
JobSpec.create(job_template_type: 'GooddataExtract', job_template_attributes: { gooddata_pid: 'abcdefg', gooddata_reports_attributes: { '1' => { name: 'george', report_oid: '123456' } } })
JobSpec
和GooddataExtract
记录创建得很好,但不是GooddataReport
记录。没有错误消息或任何内容,它们无法创建。
我可能缺少什么想法?
答案 0 :(得分:0)
build_job_template
课程中的JobSpec
方法。这是我accepts_nested_attributes_for
根据accepts_nested_attributes_for with belongs_to polymorphic使用多态模型的方式。我在SO答案中引入了一个变体,它阻止了嵌套属性在层次结构中传递。解决了这个问题后,它按预期工作了!
class JobSpec < ActiveRecord::Base
belongs_to :job_template, polymorphic: true, dependent: :destroy, inverse_of: :job_spec
accepts_nested_attributes_for :job_template
def build_job_template(params)
klass = job_template_type.constantize
self.job_template = klass.new(params)
end
end