Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::Base before_validation with conditional not triggered

I'm using before_validation to ensure the state of my User model.

before_validation :renter, if: 'resident? && active? && unit.present? && units.empty?'

The conditional is true when I tried with a new record.

user.resident? && user.active? && user.unit.present? && user.units.empty?
=> true

And the callback works perfectly without the conditional.

However, using the callback with the conditional does not work.

user = User.new(resident_attr_except_resident_type)
user.save
=> false
user.errors.full_messages
=> ["Resident type can't be blank"]

user.renter
=> #<User ..., resident_type: 0> # resident_type 0 because is a enum
user.save
=> true

Just to clarify, the renter method does the following:

def renter
  self.resident_type = :renter
  self
end

def renter!
  renter.save
end

Is there anything that I am missing?

I suspect two things, 1) the conditional and 2) the return from renter and me misunderstanding how before_validation works.

like image 262
fbelanger Avatar asked Aug 17 '26 08:08

fbelanger


1 Answers

you may try this...

before_validation :renter, if: :check_renter?

def check_renter?
  resident? && active? && unit.present? && units.empty?
end
like image 172
Sourabh Ukkalgaonkar Avatar answered Aug 18 '26 22:08

Sourabh Ukkalgaonkar