Adrian M.
Adrian M.

Reputation: 91

How do you handle type/code columns (non-STI) with AR?

I was discussing this pattern with a colleague and everyone seems to have their own take ont this. Thought using a type/code attribute seems to be a pretty common case, there's no standardized solution for it. I wonder what is yours?

Say you have a non-Single Table Inheritance type/code column on a ActiveRecord model. What do you use to specify types and create accessors, scopes, etc. A hash of symbols, a hash of codes, plain constants or...?

Something like the following:

class Listing < ActiveRecord::Base
  LISTING_TYPES = {
    :sale  => 1,
    :rent  => 2,
    :lease => 3,
  }

  validates :listing_type, :inclusion => {:in => LISTING_TYPES.values}
end

Thanks in advance.

Upvotes: 0

Views: 59

Answers (1)

Jordan
Jordan

Reputation: 1238

I use the simple_enum gem.

class Listing < ActiveRecord::Base
  as_enum :types, {:sale => 0, :rent => 1, :lease => 2}
end

The gem creates all the finders for you so you can query by the types and not the index:

Listing.find_by_type(:sale)

Upvotes: 1

Related Questions