rubyonrailsin

A Ruby and Rails talk

Wednesday, March 10, 2010


Re: [Rails] Using store values from drop down list

by rubyonrailsin 0 comments



Share this post:
Design Float
StumbleUpon
Reddit

# model code

 CLUB_TYPES = [
# Displayed stored in db
 [ "Public" , "pub" ],
 [ "Village" , "vil" ],
 [ "Private" , "pvt" ]
 ]

I would change that as follows:

CLUB_TYPES = {
  "pub" => "Public",
  "vil" => "Village",
  "pvt" => "Private"
}
 
 validates_inclusion_of :club_type, :in =>
         CLUB_TYPES.map {|disp, value| value}

So that becomes:

validates_inclusion_of :club_type, :in => CLUB_TYPES.keys
 
#view code

 <%= f.select :club_type, Club::CLUB_TYPES, :prompt => "Select a Club
Type" %>

I think when using a hash you need to invert it, something like this:

 <%= f.select :club_type, Club::CLUB_TYPES.invert, :prompt => "Select a Club
Type" %>

You may need to play with that a little bit...  I can't remember and don't have time to test it at the second...
 
This works fine for getting data into the database.

My question: Is there a helper to get the display value back from the
database? If not, could somebody show me how to correct the following
to get the display value rather than the stored value.
 
 <b>Club Type:</b>
 <%= @club.club_type %>

<%= Club::CLUB_TYPES[@club.club_type] %>

(or more likely a method on the model call club_type_description or something similar that does the same thing).

Cheers,


Andy

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment

Subscribe feeds via e-mail

Blog Archive