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
Comments left...
Well… thanks man! ;) Fast and precise…
Sebastien at 01 Apr 08 at 07:29
Thanks a lot, you solve my problem…
GIovanni at 07 Jul 08 at 02:04
Thanks a bunch. I was about to embark on an n:n relationship that would have cost me a ton of overhead.
mdc at 06 Mar 09 at 18:25
Very Very Good =) tnks
Luiz Carvalho at 24 Jul 09 at 07:18
Articles Archive →
Got something to say?