audited icon indicating copy to clipboard operation
audited copied to clipboard

The required validation which comes from 'belongs_to' in Rails 5 doesn't work

Open kyamaguchi opened this issue 6 years ago • 1 comments

Tested on the sample app. https://github.com/kyamaguchi/required_validation_from_belongs_to

Rails 5 requires relation with belongs_to by default. https://github.com/rails/rails/issues/18233

But it doesn't work after adding 'audited'.

$ rails console

> User.new(name: 'Foo').valid?
 => true

Before adding 'audited' gem,

> Company.create(name: 'Test')
> User.new(name: 'Foo').valid?
 => false
> User.new(name: 'Foo', company: Company.first).valid?
 => true

I tested on the different versions of Rails on branches on the sample app and it works fine with rails 5.1. It doesn't work with rails '>= 5.0.0, ~> 5.0.0'.


Simple solutions are

  1. Upgrading Rails to 5.1

  2. Add required: true option

class User < ApplicationRecord
  belongs_to :company, required: false

kyamaguchi avatar Sep 05 '17 04:09 kyamaguchi

From memory this was to do with ActiveRecord being initialised way before the Rails Default initialiser file is run (due to a particular gem touching it early on). The solution is to configure it earlier in the boot process, or as you say, just keep on upgrading through to Rails 5.1.

brendon avatar Sep 03 '19 02:09 brendon