activerecord-session_store icon indicating copy to clipboard operation
activerecord-session_store copied to clipboard

Drops validation from belongs_to relations in Rails 5

Open mvz opened this issue 8 years ago • 5 comments
trafficstars

In Rails 5, a belongs_to relation is automatically validated as required. Adding activerecord-session_store to the Gemfile of a Rails 5 project removes this automatic validation.

This can be reproduced very easily by creating a Rails 5 project with two related models:

rails new quuz
cd quuz
rails g model foo name:string
rails g model bar name:string foo:references

In the rails console or a test, it can now easily be verified that a Bar object is invalid without a Foo object:

Bar.new.valid?                # => false
Bar.new(foo: Foo.new).valid?  # => true

If activerecord-session_store is added to the Gemfile like so,

gem 'activerecord-session_store'

the results are different:

Bar.new.valid?                # => true
Bar.new(foo: Foo.new).valid?  # => true

mvz avatar Dec 18 '16 08:12 mvz

I've done some debugging, and this seems to have to do with ActiveRecord::Base being loaded before config/initializers/new_framework_defaults.rb is loaded. If I change the following line in that file:

Rails.application.config.active_record.belongs_to_required_by_default = true

to:

ActiveRecord::Base.belongs_to_required_by_default = true

then the validation is restored.

mvz avatar Dec 18 '16 08:12 mvz

Hope to have this fixed soon.

mauro-ni avatar Dec 19 '16 16:12 mauro-ni

Is this still an issue? Seems kinda disastrous.

jrochkind avatar Oct 04 '18 21:10 jrochkind

I just tried and it no longer occurs with Rails 5.2 and activerecord-session_store 1.1.1.

mvz avatar Oct 05 '18 07:10 mvz

It also does not occur with Rails 5.1.6 and activerecord-session_store 1.1.1.

However, it does still happens with Rails 5.0.7 and activerecord-session_store 1.1.1.

I think projects that have migrated to Rails 5.0 and then to 5.1 and 5.2 may also be affected if they haven't removed config/initializers/new_framework_defaults.rb.

mvz avatar Oct 05 '18 08:10 mvz