Posted over 6 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:

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.

#=> "User must exist"

It could be enabled or disabled in application configuration.

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

Owner of this card:

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