Reputation: 7683
I've a select that has to provide some decimal values (percentages) for an accounting application.
The values are like 10, 20, 22.5.
The problem is that want to display the first two values with no decimal part, the third with it.
In the simple_form_for documentation, in the Collections section, it talks about a label_method
, and i guess it would solve the problem.
Can you provide an example of usage of such a method?
It would be enough, but for clarity my simple_form_for is something like this :
<%= simple_form_for(@company) do |f| %>
...
<%= f.input :percentage, :collection=>[BigDecimal(10),BigDecimal(20),BigDecimal(22.5,3)]%><br />
...
And here is what i get:
Upvotes: 0
Views: 200
Reputation: 6025
Summarized, label_method allows you to define a method, which is called for each of the items in the given collection, and of which the result is used to display the item
Either you give a symbol as label method, like
label_method: :method_to_be_called
or you define the method in place, like
label_method: lambda { |value| calculated_label }
In your case, I would define the collection as
[ [BigDecimal(10), 0], [BigDecimal(20), 0], [BigDecimal(22.5, 3), 2] ]
and the label_method as
label_method: lambda { |value| number_with_precision(value[0], precision: value[1]) }
You probably also need a value_method, returning the right result to your server, something like
value_method: lambda { |value| value[0] }
Upvotes: 1