Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails check if field value is the default value for that field

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.

like image 969
linkyndy Avatar asked Jan 07 '16 15:01

linkyndy


2 Answers

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?
like image 122
Kristján Avatar answered Nov 07 '22 06:11

Kristján


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?

like image 31
Doon Avatar answered Nov 07 '22 07:11

Doon