Validating composed_of

How do I validate a composed_of attribute in my model?

I have a product model with:

composed_of :price, :class_name => 'Money', :mapping => %w(cents cents)

This maps the price attribute to the Money
( class. I want to make sure that
the price only contains a price to 2 decimal places i.e. 1.25. This is
because if someone enters 1.256 then the price ends being 1.26.

The standard validations that I’ve tried don’t work.
validates_numericality_of complains of a lack of

How do you validate these attributes?

Many thanks,

Some more information might help :slight_smile: This is how I create the new object.

@product = = params[:product][:name]
@product.price = params[:product][:price].to_money

So, correct me if I’m wrong, the price parameter gets converted to a
money object straight away (before validation is triggered). If you
enter, for example, “abcd” into the price param, when the .to_money
method is called, the money object will be 0.00.

The problem is that if someone enters 1.256 then the price ends being
1.26 because the money object automatically rounds up the value. So, I
need to validate the parameter before it gets converted into a money
object. I thought I may be able to use _before_type_cast, but
this doesn’t exist for the money object.

Any ideas would be appreciated.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs