Helpful for creating lookup-table-like rails models
Latest commit 7fac848 Jul 31, 2012 @crx crx check for existence of attribute setter in




Provides an easy means for creating models that act like enumerations or lookup tables. You can specify the lookup values in your Rails models and can lazily push these to the associated db tables (or not). Also dynamically adds helpful class-level methods to access singleton instances of each value in your lookup

What to do

Rails models

Defining a lookup model

In your model, do something like:

def MyLookup < ActiveRecord::Base
  VALS = [ { :id => 1, :name => "value 1", ... other attributes },
           { :id => 2, :name => "value 2", ... other attributes },
           ... other lookup values ...
  acts_as_lookup :values => VALS, ... other options ...

Associating a model with a lookup model

In your model, you can specify an association to a lookup using has_lookup:

def MyModel < ActiveRecord::Base
  has_lookup :my_lookup

Alternatively, you can explicitly state the class name of the associated lookup:

def MyModel < ActiveRecord::Base
  has_lookup :my_association, :class_name => 'MyLookup'

Alternative: table-less lookups and associations

TODO: probably won't work yet…at least need to add an _id attribute to the associating class.…

Other (FUTURE)

Some work is yet to be done to support general classes using acts_as_lookup


acts_as_lookup accepts an options hash with one required key: :values, which is an array of hashes that contain lookup data (see above).

Other options available:


Fetches existing records from the db and merges them into the cached values (default true).


Writes any missing values to the db (default true).


Defines query methods on instances of the lookup model for checking the identity of a value (default false). For example:

def Status < ActiveRecord::Base
  VALS = [ { :id => 1, :name => "active", },
           { :id => 2, :name => "disabled", }
  acts_as_lookup :values => VALS, :add_query_methods => true
end # => true # => false



Run rake spec to run the (rspec) tests. You should add tests for anything you touch.