views:

70

answers:

1

I'm looking for advice here:

I have two tables in legacy scheme, A and B, joined on A.somename = B.othername. Both of those columns are strings. So how do I set up relations between them in rails (v2.1.0)? Given that A has many B's, what would be the best practice:

  1. use :finder_sql and just write a SQL select,

  2. configure the relation through other parameters (how? I know I can set :foreign_key = 'othername', but that will just try to set up a A.id = B.othername relation - what can I do to set up the correct one?),

  3. something else that has not crossed my mind.

So, what would you suggest?

+1  A: 

If you're stuck with Rails 2.1 for some reason, the best option seems to be using set_primary_key, like this:

class A
  set_primary_key 'somename'
  has_many :bs, :foreign_key => 'othername'
end

There is also an alias that lets you use attribution-like syntax for that (self.primary_key = 'somename').

By the way, if you're able to upgrade to 2.3, you can use the primary_key option directly with has_many, like this:

has_many :debitos, :primary_key => 'somename', :foreign_key => 'othername'

If you choose to use this, you won't need to declare the primary key for the class using set_primary_key.

Thiago Arrais
Thank you - the second example is what I was trying to unsuccessfully find in the 2.1 API docs :) Sadly, upgrade to 2.3, while planned, is not an option right now. However, I found out that this works in 2.1: Class A set_primary_key :somename has_many :bs, :foreign_key => 'othername' end
Toms Mikoss
Answer edited to include Toms' own findings. I think this version will be more useful for future users
Thiago Arrais