Rails select helper method
My setup: Rails 3.0.9, Ruby 1.9.2
I have a global constant defined
TYPES = { "visa" => "Visa", "master" => "Ma开发者_开发百科sterCard" }
I wish to invert the values for the select method, I know it sounds silly but there is another part of my code that needs this functionality, so I'm trying to figure out if it is possible. Here's what I have so far but didn't work
<%= f.select :card_type, TYPES.each { |key, value| [value, key] } %>
Use the invert
method built-in to Hash
:
TYPES = { "visa" => "Visa", "master" => "MasterCard" }
TYPES.invert
# => {"Visa"=>"visa", "MasterCard"=>"master"}
So:
<%= f.select :card_type, TYPES.invert %>
Notes:
- Why not use symbols instead of strings for the key..
:master
instead of"master"
- The values of original
TYPES
will be used as the keys for theinvert
'edHash
, so ensure that your values are all unique.
精彩评论