7

I'm using

f.collection_select :country_id, Country.all, :id, :name)

which generates

<select name="user[country_id]" id="user_country_id">       
 <option value="1">Canada</option>
 <option  value="2">United Kingdom</option>
 <option  value="3" >United States</option>
</select>

I would like to include a prov-val and code-val attribute to the select so I can dynamically update the province labels:

<select name="user[country_id]" id="user_country_id">     
<option prov-val="Province / Territory" code-val="Postal Code" value="1">Canada</option>
<option prov-val="County" code-val="Postcode"  value="158">United Kingdom</option>
<option prov-val="State" code-val="ZIP Code"  value="2" >United States</option>

Is this possible using a collection_select ?

patrick-fitzgerald
  • 2,561
  • 3
  • 35
  • 49
  • possible duplicate of [Rails' collection_select helper method and the "Create item" option at the end](http://stackoverflow.com/questions/699165/rails-collection-select-helper-method-and-the-create-item-option-at-the-end) – Andrew Marshall Mar 05 '12 at 21:08
  • Apologies I submitted the question with a wrong title as I used the above question as a template. – patrick-fitzgerald Mar 05 '12 at 21:17

2 Answers2

10

Not sure if it's possible using collection_select, but I think using select does what you want:

<%= f.select :country_id, Country.all.map {|c| [c.name, c.id, {:'prov-val' => c.prov_val, :'code-val' => c.code_val}]} %>

This assumes that your country object has the prov_val and code_val fields.

ramblex
  • 3,042
  • 21
  • 20
  • Thanks I got it working by adding a options_for_select_with_attributes helper from: http://railsforum.com/viewtopic.php?id=38624 <%= f.select :country_id, options_for_select_with_attributes(Country.all.map {|c| [c.name, c.id, {:'prov-val' => c.prov_val, :'code-val' => c.code_val}]}) %> – patrick-fitzgerald Mar 05 '12 at 23:03
3

You shouldn't be calling the model right from the view.

It is better to use an instance variable instead:

<%= f.select :country_id, @countries.map {|c| 
  [c.name, c.id, {:'prov-val' => c.prov_val, :'code-val' => c.code_val}]
} %>
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Gonzalo Robaina
  • 367
  • 3
  • 15