Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number in a ruby on rails controller, number_with_delimiter works only in views

I would like to format a number in a controller before inserting it into a string. But the function number_with_delimiter() does not work in a controller. I need the string to send to a javascript plugin.

I could run the code in the view, but I guess that is not the best option.

@mycarousel_itemList = @mycarousel_itemList + "{url: '" + p.photo.url(:thumb) + 
"', price: '" + p.price.to_s + " €'}," 

Is there an alternative function to change the format of p.price?

like image 241
Michael Torfs Avatar asked Aug 29 '10 18:08

Michael Torfs


1 Answers

To answer your question directly, include the following in your controller (typically near the top, below the class declaration):

include ActionView::Helpers::NumberHelper

You could also include this module in the model (whatever class p is), and then write a function to return the formatted price.

The best place for code like this, however, is in a helper, not the controller. The helper would be called from the view. Your controller should be as short as possible and not include any view logic at all.

like image 134
wuputah Avatar answered Oct 16 '22 21:10

wuputah