Module: Hopsoft

Defined in:
lib/hopsoft/acts_as_lookup.rb

Overview

This plugin allows you to painlessly move away from column based lookups to normalized lookup tables.

Simply add “acts_as_lookup” to your lookup table models.

The assumed schema inclueds a “name” column which is used as the “key column”. The “key column” is the column that holds the values that are used to key off of. The “key column” allows you to code against expected values in the database rather than hard coding with primary key values.

This is generally safe considering that lookup data is relatively static.

Consider the following schema:


addresses

* id
* street
* state_id
* zip

states

* id
* name => "UT, GA, IL, etc..."
* description

Here are some examples of what this plugin provides when working with a lookup table directly:

Obtain id from a lookup table like so:

utah_id = State.ut(:id)

Obtain the description like so:

utah_desc = State.ut(:description)

The real power comes with models that contain “belongs_to” relationships to parents that act_as_lookup. These models implicitly mixin some additional behavior that make working with lookup tables as simple as using columns directly on the table itself.

For example:

You can select with the following syntax:

Address.find_by_state("UT")

You can also assign like so:

addr = Address.new
addr.state = "UT"

If a state with “UT” doesn’t exist in the states table, one will be implicitly created. The requirement being that the model validates correctly. In this case only a name is assigned.

Defined Under Namespace

Modules: ActsAsLookup