ruby-on-railsruby-on-rails-5collection-select

Rails 5 collection_select: Showing multiple attributes in one column


I'm trying to make a collection select which shows two attributes from two different models.

I want to select an account. The account has a name and an owner. The owner is a model which also has the attribute name. When using the collection select I want it to show: account.name + owner.name. This is currently the collection_select I have which only shows the account.name

  <div class="field">
    <%= f.label :to_account_id %>
    <%= f.collection_select :to_account_id, Account.all, :id, :name %>
  </div>

ex: A account has name Main account and the owner of the account is Stan, when selecting it should show Stan - Main account.

worked with:

    <%= f.collection_select :to_account_id, Account.all.map{|a| ["#{a.owner.name} - #{a.name}", a.id] },:second,:first %>

Solution

  • Try following code

     <%= f.collection_select :to_account_id, Account.all.map{|a| ["#{a.name} - #{a.owner.name}", a.id] } %>