Number_to_currency inside model


#1

I was wondering if this is possible.

I have a model (Item) that contains products. These products have prices
that I’d like to format using number_to_currency. Rather than doing this
several times inside the view, I thought it might be nice to do it once
inside the model.

The item table has an field called regular_price which holds a currency
amount. I would like to do something like what’s below, but I get the
following error message:

undefined method `number_to_currency’ for #Item:0x2479430

Here is the model.

class Item < ActiveRecord::Base
has_many :item_attributes, :order => ‘a_order’

def regular_price
number_to_currency(self)
end
end

Not sure why it’s not finding the number_to_currency helper.

Thanks!


#2

David:

number_to_currency is a Rails method defined in
ActionView::Helpers::NumberHelper.

Here’s the link to the doc: http://api.rubyonrails.org/classes/
ActionView/Helpers/NumberHelper.html

Because it’s part of ActionView, it’s normally available to View
objects but not Model objects.

I know it’s not the answer for which you’re hoping. Some might argue
that a function that displays a formatted value belongs in the View
layer rather than the Model layer. Others might argue against this!
It would be nice to hear what people think about stuff like this.

Hope it helps,

-Anthony