Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional default value in Rails (Mongoid) model

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

like image 801
Michael Discenza Avatar asked Feb 09 '23 21:02

Michael Discenza


1 Answers

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 }
like image 58
Michael Discenza Avatar answered Feb 15 '23 15:02

Michael Discenza