views:

39

answers:

2

I have a kind of legacy db structure with rails. It has a structure like:

apples
    id:
    number:
  oranges
    apple_id: (links to apples.number)
  pears
    apple_id: (links to apples.id)

Models like:

Apple  has_many :oranges, :foreign_key => ?, :primary_key => ?
       has_many :pears
Orange belongs_to :apple, :foreign_key => ?, :primary_key => ?
Pears  belongs_to :apple

I'm stuck with how to write the association. I'm having difficulty understanding the documentation on foreign keys and primary keys and which goes with has_many and belongs_to

A: 

:foreign_key

Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and "_id" suffixed. So a Person class that makes a has_many association will use "person_id" as the default :foreign_key.

:primary_key

Specify the method that returns the primary key used for the association. By default this is id.

everything depends on rows in your tables

Bohdan Pohorilets
Did I get your DB sctucture ?
Bohdan Pohorilets
I've edited my question to explain the models better.
danielsherson
As I see from your question you have conventional rows in your table so I can't get why do you want to specify values of :foreign_key and :primary_key
Bohdan Pohorilets
A: 

The solution ended being:

Apple  has_many :oranges, :primary_key => :number
       has_many :pears
Orange belongs_to :apple, :primary_key => :number
Pears  belongs_to :apple

I was led down the wrong track by assuming :foreign_key had something to do with something.

danielsherson