Validating composed_of

Hi,
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
(http://dist.leetsoft.com/api/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
“price_before_type_cast”.

How do you validate these attributes?

Many thanks,
Jordan

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

@product = Product.new
@product.name = params[:product][:name]
@product.price = params[:product][:price].to_money
@product.save

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.

Cheers,
Jord

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