Paulus Paulus - 2 years ago 70
HTML Question

Best practice for custom text_method in collection_select?

I have Rails app with a use case to display prices in a collection_select dropdown box. For instance, names of products and their prices, or clients and amounts owing.

I well know it's bad MVC practice to simply include the relevant helpers to get access to functions like number_to_currency, but the best I can do with a custom method on the Product or Payment model is get a value that looks like $20.2. So, it's readable but sub-optimal in that most users of the system will be expecting twenty dollars and twenty cents to be represented as $20.20.

Does anyone have any suggestions for easily customising the text_method of a collection_select?

Answer Source

Abandon ship with the collection_select method, and just use select in your view:

<% options = @payments.each { |p| number_to_currency(p.price), } %>
<%= :payment, options %>

Since you're in the view, everything you'd expect is there, both model and helper methods.

I'm making assumptions on your HTML since you didn't give a specific example, but I think the code block above is everything you need to get going. For more details:

If you are married to collection_select, you could always roll your own number formatter for currency; shouldn't be difficult with pure Ruby. But, the method above will be more powerful in the long run and afford your more options with helpers down the line, and let you use functions consistently across views.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download