Monday, September 04, 2017

Rails 5 makes belongs_to association required by default

In Rails 5, whenever we define a belongs_to association, it is required to have the associated record present by default. This change will have some impact if you are migrating an existing Rails 4 application in to Rails 5 and foreign key is not mandatory in your application. It will trigger validation error if associated record is not present.

For example, if your User model has city_id as foreign key, then if you create user without adding city_id then rails 5 will throw validation error.

class User < ApplicationRecord
  belongs_to :city

How to achieve this behavior before Rails 5

In Rails 4.x world in order to add validation on belongs_to association, we need to add option required: true.  By default is false

class User < ApplicationRecord
  belongs_to :city, required: true

Turn off this default behavior in Rails 5

If we want to turn off this behavior we can use :optional => true . When set to true, the association will not have its presence validated.

class User < ApplicationRecord
  belongs_to :city, optional: true

You can turn off this in entire application by setting

Rails.application.config.active_record.belongs_to_required_by_default = false

No comments:

Post a Comment