1

I have an app with three models. At the highest level is a JobSpec

class JobSpec < ActiveRecord::Base
  belongs_to :job_template, polymorphic: true, dependent: :destroy, inverse_of: :job_spec
  accepts_nested_attributes_for :job_template
end

This has a polymorphic association with a job_template, one of which is a GooddataExtract template

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

which in turn has a one-to-many relationship with a GooddataReport

class GooddataReport < ActiveRecord::Base
  belongs_to :gooddata_extract, inverse_of: :gooddata_report
end

I'm having trouble constructing a parameter hash that will create the GooddataReport items. When I use

JobSpec.create(job_template_type: 'GooddataExtract', job_template_attributes: { gooddata_pid: 'abcdefg', gooddata_reports_attributes: { '1' => { name: 'george', report_oid: '123456' } } })

The JobSpec and GooddataExtract records get created just fine, but not the GooddataReport records. There are no error messages or anything, they just fail to get created.

Any ideas what I might be missing?

1 Answers1

0

Found it! Unfortunately I didn't provide the full example needed to figure out the issue. I had forgotten about the build_job_template method that was in the JobSpec class. This is way I was getting accepts_nested_attributes_for to work with a polymorphic model according to accepts_nested_attributes_for with belongs_to polymorphic. I had introduced a variation on that SO answer that was preventing nested attributes from getting passed down the hierarchy. After resolving that issue, it's working as expected!

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
Community
  • 1
  • 1