I have a field named number
on the Address
model, which has a default of 0
set at database level. If I do Address.new.number
, I will get 0
back.
Now, I want to trigger a before_create
callback only if number != <default value>
. So, I will have before_create :callback, unless: <condition>
. How can I check this using some Rails "logic"? I know I can compare to 0
, but I'd rather compare to a dynamical value, as retrieved by Rails.
Default values are accessible in Address.column_defaults
as a hash of {"column" => default}
:
Address.column_defaults
#=> {"number" => 0, "street" => nil, ...}
You can also use the <attribute>_changed?
methods Rails provides. This will be false
unless you initialize the object with a non-default value.
Address.new.number_changed? #=> false
Address.new(number: 1).number_changed? #=> true
So your before_create
can look like:
before_create :callback, if: :number_changed?
what about using the columns has?
Address.columns_hash['number'].default
should give you want
so maybe something like this
before_create :callback, unless: Proc.new { |address| address.number == Address.columns_hash['number'].default }
But this seems kinda odd over using something like number_changed?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With