Debian
Debian

Reputation: 107

Formatting data after collection from the database

In the following way I can format the data when I assign to the object:

def cost=( w )
    super w.gsub( ",", "." ).gsub( /[^0-9\.]/, "" ).to_f
end

Is there a simple way to do it the other way? I mean that when I get the price from the database automatically formats the data like in the example above?

Upvotes: 0

Views: 64

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

Sure. In your view just use number_with_delimeter, e.g.:

<%= number_with_delimiter @record.cost %>

This assumes you have your Rails locale set to the appropriate local for the formatting you want to use. Otherwise you can force a local, e.g.:

<%= number_with_delimiter @record.cost, :locale => :fr %>

By the way, you could do this in your model by overriding cost, e.g.:

def cost
  some_formatting_method self[:cost]
end

...but that would be breaking with MVC principles. It's best, as I said, to do this in your view, with the built-in helpers.

Upvotes: 1

Related Questions