views:

22

answers:

1

Hi all,

I have a relatively simple problem. I have a model named Item which I've added a status field. The status field will only have two options (Lost or Found). So I created the following array in my Item model:

STATUS = [ [1, "Lost"], [2, "Found"]]

In my form view I added the following code which works great:

<%= collection_select :item, :status, Item::STATUS, :first, :last, {:include_blank => 'Select status'}  %>

This stores the numeric id (1 or 2) of the status in the database. However, in my show view I can't figure out how to convert from the numeric id (again, 1 or 2) to the text equivalent of Lost or Found.

Any ideas on how to get this to work? Is there a better way to go about this?

Many thanks, Tony

+2  A: 

You can define a method in your Item model:

class Item < ActiveRecord::Base
  #
  def status_str
    Item::STATUS.assoc(status).last
  end
end

And use it:

item.status_str # => "Lost" (if status == 1)

Or you can check out enum_fu plugin:

class Item < ActiveRecord::Base
  #
  acts_as_enum :status, ["Lost", "Found"]
end

and then item.status gives you string value:

item.status # => "Lost"
Voyta
Perfect! I ended up going with your first suggestion as it isn't much work and I'd like to keep the code as simple as possible. THANK YOU!
slythic