Help us understand the problem. What is going on with this article?

Rails5からbelongs_to関連はデフォルトでrequired: trueになる

More than 3 years have passed since last update.

railsのコードを読んでいたときに目にしたのでメモ。

rails - belongs_to should default to required: true #18233

Add config/initializers/active_record_belongs_to_required_by_default.rb

Newly generated Rails apps have a new initializer called active_record_belongs_to_required_by_default.rb which sets the value of the configuration option config.active_record.belongs_to_requred_by_default to true when ActiveRecord is not skipped.

As a result, new Rails apps require belongs_to association on model to be valid.

This initializer is not added when running rake rails:update, so old apps ported to Rails 5 will work without any change.

Josef Šimánek

-- railties/CHANGELOG.mdより --

どう変わるのか

Rails4以前ではbelongs_to関連の外部キーでnilを許可しないようにするために

models/article.rb
class Article < ActiveRecord::Base
  belongs_to :user, required: true
end

とか、

models/article.rb
class Article < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user
end

という書き方でvalidationをしていました。(後者を用いる人は少ないかもしれませんが。)

dhh兄貴曰く、

belongs_to関連の外部キーでnilを許可しているケースは珍しいのに、デフォルトではrequired: falseな(つまり、nilを許可している)状態になっている。これをデフォルトでrequired :trueにして、validationを外したい場合は任意で外せるようにしよう!

required: falseにしたい時はoptional: trueと書けるようになる。

models/article.rb
class Article < ActiveRecord::Base
  belongs_to :user, optional: true
end

また、古いアプリケーションをrake rails:updateでアップデートした場合はbelongs_to関連においてデフォルトでバリデーションさせるためのイニシャライザ追加されないため、特に変更を行わなくてもこれまでどおり動作する。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした