Skip to content

Custom foreign keys in ruby on rails

Posted on 21 June 2006

Custom foreign keys in Rails are handy if you have a legacy database where you cannot change table/field names.

In my case it wasn't to do with a legacy db; I wanted to create a foreign key that pointed to the same table as another foreign key.

The best way to explain this is by example. I have a table that stores data relating to swaps. Each swap relates to two adverts. So I needed two foreign keys for every swap, one each for the two adverts.

So in my swaps table I have fields:

offered_advert_id 
advert_id

In my swap model:


class Swap < ActiveRecord::Base
 belongs_to :advert
 belongs_to :offered_advert, :class_name => "Advert", :foreign_key => 'offered_advert_id'
end

In my advert model:


class Advert < ActiveRecord::Base
 has_many :swaps
 has_many :offered_swaps, :class_name => 'Swap', :foreign_key => 'offered_advert_id'
end

advert_id follows the typical rails assumptions and therefore the relationship between a swap and the advert_id is as expected.

The complication is with the offered_advert_id field which needs the additional relationship entered into both models.

Essentially it doesn't matter what you call the :has_many or the :belongs_to but you need to be specific about the :class_name => which must relate to the two models involved and the :foreign_key => must point to the field you want the relationship to use.

Using the above code gave me the method such as:

swap.offered_advert

View the snippets archive ››

2 comments made

Sebastien commented on 01 Apr 08 at 07:29

Well… thanks man! ;) Fast and precise…

GIovanni commented on 07 Jul 08 at 02:04

Thanks a lot, you solve my problem…

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com