slythic
slythic

Reputation: 311

Getting the value from an array in the model in rails

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

Upvotes: 0

Views: 595

Answers (1)

Tatjana N.
Tatjana N.

Reputation: 6225

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"

Upvotes: 3

Related Questions