robotdana
robotdana

Reputation: 532

unconventional foreign keys in rails

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

Upvotes: 0

Views: 223

Answers (2)

robotdana
robotdana

Reputation: 532

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.

Upvotes: 0

Bohdan
Bohdan

Reputation: 8408

: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

Upvotes: 0

Related Questions