Search code examples
htmlruby-on-railsmodel-view-controllercollection-select

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?


Solution

  • I ended up building on GoGoCarl's suggestion, but moving the array generation to a helper:

    module PaymentsHelper
      def invoices_for_payment_select(invoice)
        @invoices.collect { |i| ["#{i.client.name} - #{number_to_currency(i.outstanding)}", i.id] }
      end
    end
    

    This way I can reuse the dropdown box should I need to and keep the view neat.