Belongs-to relationship question

High level question, with a “belongs-to” relationship … you
usually put the primary key of the parent object into the table of the
child. I would like to know if there is a way to reference the parent
object, via something else than the primary key. Here is a simple
example:

model:
Class Property “belongs-to” class Neighborhood
Class Neighborhood “has-many” class Properties

SQL DB:
Properties Table contains a field called AREA.
Neighborhood Table contains a field called AREA_ID

Property.AREA == Neighborhood.AREA_ID // these two data points match

Can I reference the Neighborhood Object from the Property Object,
without adding the primary key from the Neighborhood table to the
property table? Ideally, I would like to write code like: <%
property.neighborhood.name %>, as I would be able to if I added the
primary Neighborhood id key to the Property table.

Thanks for any insight!

LAB

On 10/10/07, LAB [email protected] wrote:

primary Neighborhood id key to the Property table.

Thanks for any insight!

Is Neighborhood.area unique for a given neighborhood, i.e. not two
neighborhoods have the same area.

If so then it sounds like area should be the primary key for
neighborhoods. If you have to name it area then you need to do
something like (this is off the top of my head and untested):

  1. Make it the actual primary key, if you are using migrations use the
    ;id => false option on create table something like:

    CreateNeighborhoods << ActiveRecord::Migration
    def self.up
    create_table :neighborhoods, :id => false do |t|
    t.add_column :AREA_ID, :primary

Although I’m guessing that this is probably a legacy DB otherwise why
are you fighting ActiveRecord?

Note that this assumes that it’s an autoincrement integer, if not
you’ve got some more working against conventions to figure out on your
own.

  1. override the conventions in the Neighborhood model

    class Neighborhood << ActiveRecord::Base

     primary_key = "AREA_ID"
     has_many :properties
    

    class Property
    belongs_to :neighborhood, :foreign_key => “AREA_ID”


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

On 10/10/07, Rick DeNatale [email protected] wrote:

  1. override the conventions in the Neighborhood model

    class Neighborhood << ActiveRecord::Base

     primary_key = "AREA_ID"
    

This should be:

      set_primary_key  "AREA_ID"

I DID say that it was off the top of my head.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/