Ben
Ben

Reputation: 802

Unable to create Valid ActiveRecord Model Due to Reference Error

I have a gem that has two active record models Model A and Model B. Model B MUST have a reference to Model A if another field is true and CANNOT have a reference to Model A if that other field is false.

validates_presence_of :model_a_id, if: :external
validates_absence_of :model_a_id, unless: :external

Our gem is tested using combustion. When running the engine or gem through combustion everything works fine. We can create Model B in all instances. When our gem is consumed by our other application, you cannot create Model B if the external is false, as it gives you:

1 error prohibited this model_b from being saved:
  Model A must exist

This previously worked prior to being on Rails 5. After investigating why this could be happening I landed on this configuration that is present in the initializers. This configuration exists in the application that consumes our gem, but not the gem itself.

Rails.application.config.active_record.belongs_to_required_by_default = false

If I put this configuration item in my gem and set it to false, nothing changes. When ran through combustion I can create Model B with external set to false. When ran through the application, I still cannot create Model B, with the same error as above.

When I put this configuration item in my gem and set it to true, I can no longer create Model B, with the same error as when I run the gem through the application. The same result happens with the application.

I've been stumped on what to do to resolve this issue and any help would be appreciated.

Upvotes: 0

Views: 59

Answers (1)

Ben
Ben

Reputation: 802

I believe I have figured out how to fix this. I'm unsure why the configuration in the initializers didn't work, but on the belongs_to :model_a I changed it to:

belongs_to :model_a, optional: true

Upvotes: 1

Related Questions