Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra html attributes to a Rails collection_select

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 ?

like image 826
patrick-fitzgerald Avatar asked Mar 05 '12 21:03

patrick-fitzgerald


2 Answers

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.

like image 65
ramblex Avatar answered Nov 15 '22 07:11

ramblex


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}]
} %>
like image 35
Gonzalo Robaina Avatar answered Nov 15 '22 09:11

Gonzalo Robaina