views:

55

answers:

3

I have a model like this...

Receipt
-------
amount:int  # => An amount of money stored as cents.

But in the view I have these fields...

amount_dollars
amount_cents

So mass assignment won't work there.

What is the standard way to deal with this situation? Where do you put the code that converts the incoming values into an amount of cents?

+1  A: 

add attr_accessors for amount_dollars and amount_cents. use a before_save callback to update amount.

Ben Hughes
Thanks, that worked great.
Ethan
A: 

You can define a so-called virtual attribute for each of these fields in the view.

def amount_dollars=(value)
  ...
end

def amount_cents=(value)
  ...
end

These handle the values that come from the form submitted. In each of these methods you modify your model's amount attribute appropriately.

neutrino
How does that work? If you call amount_dollars=(value) without knowing what cents is supposed to be you'll set amount incorrectly.
Ethan
+3  A: 

You may be looking for virtual attributes?

There's a railscast about it.

You can watch it here.

There's also the text-based version of it in case you like it better.

Carlos Lima
+1 Definitely a good candidate for virtual attributes.
Simone Carletti
Thanks. Watched the Railscast and tried virtual attributes, but it was problematic because I had one DB column mapped to two UI fields, rather than the opposite.
Ethan