Using Array or Hash with Form Select and Elsewhere


#1

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!


#2

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 B. removed_email_address@domain.invalid wrote: