MikeHolford
MikeHolford

Reputation: 1931

How do I define values in options_for_select?

I have this options_for_select call:

    <%= f.select(:agents, options_for_select(@agents), {},{multiple: true, size: 10, :id => "agents"}) %>

There are only currently 2 agents in the database but they are showing up as #<Agent:0x007fc1b121c490> format. I want them to display as @agent.name and for the value to be @agent.id.

How do I edit this code above to get this? Thank you!

Upvotes: 0

Views: 63

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36880

There is actually a helper specifically for collections, options_from_collection_for_select which is to handle exactly this case.

<%= f.select(:agents, options_from_collection_for_select(@agents, 'id', 'name'), {},{multiple: true, size: 10, :id => "agents"}) %>

Upvotes: 2

Viktor Vsk
Viktor Vsk

Reputation: 327

You should directly provide what you want to use as options values and ids:
<%= f.select(:agents, options_for_select(@agents.map{ |agent| [agent.name, agent.id]}), {},{multiple: true, size: 10, :id => "agents"}) %>
Refer the documentation API
Also, probably you would like to select current value:
<%= f.select(:agents, options_for_select(@agents.map{ |agent| [agent.name, agent.id]}, @current_agent), {},{multiple: true, size: 10, :id => "agents"}) %>

Upvotes: 1

Related Questions