简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM