fbelanger fbelanger - 5 months ago 14
Ruby Question

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.

Answer
Comments