Skip to content

belongs_to associations are now validated unless 'optional: true' #34454

@brentkearney

Description

@brentkearney

After upgrading from Rails 5.0.7 to Rails 5.1.6, my Schedules model failed to validate when an associated belongs_to model is nil. The error is:

ActiveRecord::RecordInvalid:
       Validation failed: Lecture must exist

The Schedules model had:

belongs_to :lecture
validates_associated :lecture, allow_nil: true

After the upgrade, its necessary to add the optional option:

belongs_to :lecture, optional: true

Suggested addition to /guides/source/upgrading_ruby_on_rails.md:

Upgrading from Rails 5.0 to Rails 5.1

...

belongs_to associations are now automatically required: true

All model's belongs_to associations are now treated as if the required: true option is present. So if the association is optional, that must be declared, or validation will fail without the presence of the associated model record.

belongs_to :user, optional: true

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions