This may seem like an oxymoron, a "conditional default," but I was wondering if there is a way I can easily handle setting a default value for a field only in the case where the object is not of a certain type.
For instance, I have
field :object_type, type: String
field :price, type: Float, default: 0
validates :price, presence: true, numericality: { greater_than_or_equal_to: 0 }
It would be sweet if I could add a condition such as unless: ->{ object_type == "a"}
and take care of this inline. Will rails allow that or do I have to now set this conditional default with a before_create
callback?
Pseudo code for what I want to happen:
if the object_type is any other type than "a" then I want to set the default value for price to zero.
if the object type is a, I want only zero and non-negative numeric values to be acceptable
Using proc
was the way to go here
field :object_type, type: String
field :price, type: Float, default: proc { object_type== "a" ? nil : 0}
validates :price, presence: true, numericality: { greater_than_or_equal_to: 0 }
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