Kristian
Kristian

Reputation: 21840

Form_for select field, concatenating data into the display string

I am trying to use a form_for collection_select to display some select field options of account types.

Its occurred to me that it would be easier for the user if they could see the price of the type in each select option

this is my currently not-working code:

<%= a.collection_select :account_type, AccountType.all, :id, (:name+" - "+number_to_currency(:price)) %>

how can i concatenate the values so that (:name+" - "+number_to_currency(:price)) will actually work and not throw an error?

Upvotes: 2

Views: 1722

Answers (1)

anandvc
anandvc

Reputation: 82

See the documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

You can use the :text_method option to set the displayed text in the select dropdown.

In your AccountType model, define a method like this:

  def name_with_price
    "#{name} - $#{price}"
  end

Then, in your view, you can use:

<%= a.collection_select :account_type, nil, AccountType.all, :id, :name_with_price %>

Upvotes: 2

Related Questions