ruby-on-railsactiverecord

How can I skip before_validations in Rails?


I have code that updates/fixes some model data in my before_validation callbacks.

However, I'd like to be able to still run validations to see if a model is ok as-is.

More specifically, i'd like to know if a record in the database is valid or not. So I'd like to be able to load a value and ask .valid? without having my callbacks run that would affect the answer.

So, I tried this (and a few variations) but it didn't work:

skip_callback :validation, :before, unless: ->{self.changed?}

The docs for skip_callback are poor, so I'm not sure I'm using it properly. Can this be made to work?

Thanks.


Solution

  • According to APIDock skip_callback takes callback_name, then *filter_lists as arguments (then a block).

    filter_list must include your callback method name. Like this below.

    class User < ActiveRecord::Base
      validates_presence_of :name
      before_validation :set_name
    
      skip_callback :validation, :before, :set_name, unless: -> { self.changed? }
    
      def set_name
        self.name ||= 'foobar'
      end
    end
    
    #<User:0x007ffcd7165248 id: 2, name: nil, created_at: Fri, 03 Feb 2017 01:10:37 UTC +00:00, updated_at: Fri, 03 Feb 2017 01:10:37 UTC +00:00>
    
    User.find(2).valid? # returns false
    
    user = User.find(2)
    user.updated_at = Time.now
    user.valid? # returns true, because it invokes :set_name before validation