Rails and Static Lookup Tables

Rails’ ActiveRecord provides several methods to map relationships between database tables. If you need a simple lookup table, such as the following, you’re actually looking for :has_one.

# \d person
                           Table "public.person"
   Column   |  Type   |                      Modifiers
------------+---------+-----------------------------------------------------
 id         | integer | not null default nextval('person_id_seq'::regclass)
 genders_id | integer | not null

# \d genders;
                                Table "public.genders"
 Column |         Type         |                      Modifiers
--------+----------------------+------------------------------------------------------
 id     | integer              | not null default nextval('genders_id_seq'::regclass)
 gender | character varying(1) |

class Person < ActiveRecord::Base
        has_one :gender, :foreign_key => 'id'

Notice the :foreign_key parameter which isn’t normally necessary. ActiveRecord will otherwise look for a field, person_id, which doesn’t exist.

Update, August 23rd. Looks like my first foray into Rails posting makes me look like an idiot. In reality, I seem to have my relationship backwards. If instead I reverse my :belongs_to and :has_one and then make the latter a :has_many, it works. Of course, saying a person belongs to a gender sounds strange.

Having come from doing SQL directly, I still find ORM strange.

Update, January 23rd, 2007. Looks like it wasn’t just me.

One Comment

  1. Posted 8/28/2006 at 3:13 pm | Permalink

    >> Of course, saying a person belongs to a gender sounds strange.

    I don’t think it sounds strange (although I did at first). A gender is a way of grouping people, saying “a person belongs to a gender group” doesn’t sound all that odd.

Post a Comment

Your email is never shared. Required fields are marked *

*
*