Forum: Ruby on Rails Using Array or Hash with Form Select and Elsewhere

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7fc475be15e1a2f0d4eaad6fdb40caa8?d=identicon&s=25 Mike Boone (Guest)
on 2007-04-23 15:03
(Received via mailing list)
I'm working on a small project in order to learn Rails. I have a model
with a status field, which I want to be 'open' or 'closed' (I may add
some other options later). I am storing them in the database all
lowercase (later options might be abbreviated in the DB). To display
things nicely, I want them to appear as 'Open' or 'Closed' in the form
dropdown and tables where the status is displayed. Using an array or
hash, I can manage to do one or the other, but I'm not sure how to
accomplish both.

If I use an array:
STATUSES1=[['Open','open'],['Closed','closed']]

That works directly in a form using "select :status,
Thing::STATUSES1".

But I don't know how to lookup the capitalized version in the array
given the lowercase status value.

If I use a hash:
STATUSES2={'open'=>'Open','closed'=>'Closed'}

It is easy to display the formatted value in pages using:
<%= Thing::STATUSES2[thing.status] %>

I tried to use this hash in the form select, but the value/text is
backwards: it put 'Open' into the value and 'open' into the the
displayed text.

So is it better to use an array or hash for my purposes, and how do I
manipulate it to accomplish both tasks?

Thanks!
7fc475be15e1a2f0d4eaad6fdb40caa8?d=identicon&s=25 Mike Boone (Guest)
on 2007-04-23 19:34
(Received via mailing list)
I came up with a solution. I used the hash and put
Thing::STATUSES2.invert as the parameter in the form select call. I'm
still interested to know if I'm doing things the "proper" way.

Thanks,
Mike.


On Apr 23, 9:01 am, Mike Boone <boonedo...@gmail.com> wrote:
This topic is locked and can not be replied to.