LoginSignup
2
2

More than 3 years have passed since last update.

ActiveRecord単体でbelongs_to でoptional: trueを有効にする

Posted at

Rails 5.1からbelongs_toを指定した時、自動的にrequired: trueオプションが追加されpresenseのバリデーションが走るようになったことを今知った(https://github.com/rails/rails/issues/34454 )のですが(同時にrequiredオプションは非推奨になったようです)。

そして、新たにoptionalというオプションが追加され、その名の通り、これをオンにすると、presenseのバリデーションを追加しないように指定できるというもの。

要は、

class Book < ActiveRecord::Base
  belongs_to :author, optional: true
end

としておけば、Book.new author: nilとしても、検証はパスするようにできるということ。

これをRailsでなく、ActiveRecord単体で使おうとするとうまくいかなかった。調べてみたら、この機能はRailtieがRailsの初期化プロセスの中でオンにしているようで( https://github.com/rails/rails/blob/b2864a2069dfe9e3d483e16a74a9e6271759accc/railties/lib/rails/application/configuration.rb#L87 )、ActiveRecord単体で有効にするには事前にActiveRecordに設定する必要がある。

ActiveRecord::Base.belongs_to_required_by_default= true

とすれば、うまく行った。

プロジェクトでActiveRecordを単体で使うときは、設定をちゃんとしないと引っかかるところが他にもありそうだなー。

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2