dot
dot

Reputation: 496

Why select_tag displays only one column?

I have the following select_tag in my view:

   <%= select_tag :users, options_from_collection_for_select(@users, 'id','firstname' , 'lastname') %></p></br>

I want to display the firstname and lastname in the select_tag, but it always displays the first parameter after the 'id' in this case the firstname.

What I'm doing wrong?

Upvotes: 0

Views: 121

Answers (3)

Kirti Thorat
Kirti Thorat

Reputation: 53038

Use this instead

<%= select(:users, :id, @users.map {|u| [u.firstname + " " + u.lastname,u.id]}) %>

Upvotes: 1

JGutierrezC
JGutierrezC

Reputation: 4523

From Api Doc for options_from_collection_for_select you can get this:

options_from_collection_for_select(collection, value_method, text_method, selected = nil)

If you only want to display the options, that's is the right way to do it.

You only specify a 4th parameter if you want to preselect one option.

If you want to concatenate the name, you could do it as Oscar Valdez is telling you to.

Check more info for options_from_collection_for_select here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select

Upvotes: 0

Oscar Valdez Esquea
Oscar Valdez Esquea

Reputation: 920

Im confident that options_for_select only allows you to put 1) The value that you want each option to have, 2) The id or label you want that option to have.

What you'd do is, in your User model, set a method to concatenate both the user first and last name into one and then use that as your option_for_select id.

User Model

def userFullName
   self.firstname+' '+self.lastname
end

Then use it in your select_tag as this:

<%= select_tag :users, options_from_collection_for_select(@users, 'id','userFullName') %>

Upvotes: 0

Related Questions