Published on
1 min read

Rails 5 'belongs_to' associations default to required true

Authors

Rails 5.0 introduced a significant change: belongs_to associations now default to required: true. If you try to create an object with a nil foreign key, it will throw a "must exist" validation error. This might impact apps migrating from Rails 4 where foreign keys were optional.

Example

If your User model belongs to a City:

class User < ApplicationRecord
  belongs_to :city
end

Attempting to create a user without a city:

user = User.create(name: 'Shaiju')
# (0.3ms)  BEGIN
# (0.2ms)  ROLLBACK
# user.errors.messages => {:city=>["must exist"]}

How to make it optional

If you want to allow nil values, use the optional: true option:

class User < ApplicationRecord
  belongs_to :city, optional: true
end

Global Configuration

To turn off this behavior for your entire application, set the following in a new initializer:

# config/initializers/active_record_belongs_to_required_by_default.rb
Rails.application.config.active_record.belongs_to_required_by_default = false

Remember to restart your server after modifying initializers.

TwitterLinkedInHacker News