0

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

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.