Aaron A
Aaron A

Reputation: 543

"Status is Invalid" - Active Record - Rails 4.1 -> 5.2

I'm working on upgrading a Ruby 2.2.2 (Rails 4.1) app to Ruby 2.5.7 (Rails 5.2) and for a couple of models I'm getting some errors

From searching around, it sounds like there are some generic activerecord validation rules / messages? The messages are:

Status is invalid
User is invalid`

I am a novice at best with Ruby - so any suggestions on the best way to work through this error are appreciated!

Upvotes: 0

Views: 230

Answers (1)

spickermann
spickermann

Reputation: 106972

In Rails 5, whenever a belongs_to association is defined, it is required to have the associated record present by default. That means, compared to Rails 4, each belongs_to :foo association basically adds internally a validate :foo, presence: true to the code too.

You have two choices:

  • Follow the new Ruby on Rails conventions and fix your tests by adding all required associated objects to the models.
  • Switch back to the old behavior for these kinds of associations by adding , optional: true to each belongs_to :foo line in your code.

There is actually the third option to switch off this behavior in the whole application, by adding a line like this to your application.rb

Rails.application.config.active_record.belongs_to_required_by_default = true

But that means your application will not follow Ruby on Rails conventions and defaults anymore and IMHO this ofter leads to problems with a later update.

Therefore my advice is: Fix your tests now and only make those associations optional that are really optional from the user's point of view – this might take a bit longer but causes certainly less trouble in the future.

Upvotes: 1

Related Questions