Posted over 5 years ago. Visible to the public.

Models `belongs_to` association required by default.

In Ruby on Rails 5 belongs_to associations required by default so the following code:

Copy
class User < ApplicationRecord end class Post < ApplicationRecord belongs_to :user # to make it work in Rails 4.x you need to add `required: true` end post = Post.create(title: 'Hi') #=> <Post id: nil, title: "Hi", user_id: nil, created_at: nil, updated_at: nil> post.errors.full_messages.to_sentence

will throw an error.

Copy
#=> "User must exist"

It could be enabled or disabled in application configuration.

Copy
Rails.application.config.active_record.belongs_to_required_by_default = false|true

Owner of this card:

Avatar
Alexander M
Last edit:
over 5 years ago
by Alexander M
Tags:
Rails-5-0
Posted by Alexander M to Ruby and RoR knowledge base
This website uses short-lived cookies to improve usability.
Accept or learn more