-
-
Save viola/1070410 to your computer and use it in GitHub Desktop.
| -- model | |
| some sort of constant hash: | |
| HASH_NAME = { | |
| 0 => "Choose:", | |
| 1 => "On-Campus Recruiting - CSO",· | |
| 2 => "CSO Staff Referral", | |
| 3 => "Faculty Contact",· | |
| 4 => "Career Day",· | |
| 5 => "CSO Summer Job Listing",· | |
| 6 => "Alumni Contact",· | |
| 7 => "Personal Contact",· | |
| 8 => "Other"· | |
| } | |
| -- view | |
| <%= f.input :some_field, :collection => Model::HASH_NAME.sort.map {|k,v| [v,k]} %> | |
| This would output nice select with select-value as hash key and select-name as hash value, such as: | |
| <select id="form_application_job_source" class="select required" name="form_application[job_source]"> | |
| <option value="0">Choose:</option> | |
| <option value="1">On-Campus Recruiting - CSO</option> | |
| <option value="2">CSO Staff Referral</option> | |
| <option value="3">Faculty Contact</option> | |
| <option value="4">Career Day</option> | |
| <option value="5">CSO Summer Job Listing</option> | |
| <option value="6">Alumni Contact</option> | |
| <option selected="selected" value="7">Personal Contact</option> | |
| <option value="8">Other</option> | |
| </select> |
Inspired by this great gist I did the following
MY_LIST = ["Choose:", "On-Campus Recruiting - CSO", "CSO Staff Referral","Faculty Contact", "Career Day", "CSO Summer Job Listing", "Alumni Contact", "Personal Contact", "Other"]
HASH_NAME = Hash[MY_LIST.map.with_index{ |obj, i| [i, obj] }]
This let me manage the list separately and add elements if needed!
I appreciate that!
感謝你!thanks for the tip!
Thank you so much for this!! Saved me a ton of time! :)
Exactly what I needed. Thanks!
wonderful! thank you!
Thanks for this. Very useful!
sort method is no longer needed in ruby >1.9
Hashes enumerate their values in the order that the corresponding keys were inserted.
http://ruby-doc.org/core-1.9.3/Hash.html
Five years later... it has been really helpful. Gracias!
Amazingly helpful. Saved a ton of time. Thank you!
f.input :some_field, :collection => Model::HASH_NAME, value_method: :first, label_method: :last
6 years later! Thank you so much!
Again. Thanks! Exactly what I needed today.
Thanks! - Helped me troubleshoot getting my MDB select working properly:
"
<%= options_for_select(Customer::PROVINCES.map {|k,v| [v,k]}) %>
Still a relevant and very useful thread, thanks all.
6 months later, still very useful post. Thanks viola and others :).
update for my particular case
Since I needed some translation, only half of my problem was solved. So I ran into this gem https://github.com/brainspec/enumerize and voila. I don't need a collection anymore for my simple_form.