Models `belongs_to` association required by default.

Posted About 8 years ago. Visible to the public.

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
Alexander M
Last edit
Over 7 years ago
Alexander M
Tags
Posted by Alexander M to Ruby and RoR knowledge base (2016-03-30 11:55)