0

The docs state options_from_collection_for_select(collection, value_method, text_method, selected = nil) has to have elements that respond_to? the value_method and the text_method.

What if my collection is an array of hashes and I need to use some helper methods for value_method and text_method?

For example,

collection = [{
                model: "LaF"
                year: 2016,
                mileage: 1230
             },
             {
                model: "P1",
                year: 2015,
                mileage: 1311
             },
             {
                model: "918",
                year: 2015,
                mileage: 2448
             }

]

For example: I want to be able to use the I18n.interpolate("car.mileage",mileage: element[:mileage]), method on the model key of each element.

TL;DR: How to call hash key methods or other helper methods on options_from_collection_for_select elements?

absessive
  • 1,121
  • 5
  • 14
  • 36

1 Answers1

1
options_from_collection_for_select(collection, value_method, ->(element) { I18n.interpolate("car.mileage",mileage: element[:mileage]) })

The :value_method and :text_method parameters are methods to be called on each member of collection. The return values are used as the value attribute and contents of each check box tag, respectively. They can also be any object that responds to call, such as a proc, that will be called for each member of the collection to retrieve the value/text.

tlemens
  • 41
  • 1
  • 3