Custom foreign keys in ruby on rails
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
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
2 comments made
Well… thanks man! ;) Fast and precise…
Thanks a lot, you solve my problem…
Got something to say?