Has many association problem

Dear all

I have the following 2 models, with 2 difference data sources. I would
like to create a has_many relation to SX1::Request

pat = SX9::Patient.find(“123456789”)

pat.pat_encounter_group
=> 99999

By default, rails will use the PK(Primary Key) of SX9::Patient then pass
to SX1::Request. e.g.

SELECT * FROM request WHERE (request.req_encounter_group = “123456789”)

What I am expected is to override the primary_key in SX9::Patient
has_many relation with :primary_key => “pat_encounter_group”. i.e.

SELECT * FROM request WHERE (request.req_encounter_group = 99999)

But I failed to do…

Luckily, I can achieve this by defining a instance method. e.g.
def find_request_by_pat_encounter_group
SX1::Request.find_all_by_req_encounter_group(self.pat_encounter_group)
end

My question, is it possible to do this in has_many relationship? Thank
you.

module SX9
class Patient < RemoteSX9Model
set_table_name “patient”
set_primary_key “pat_encounter”

# I tried this but failed
has_many :requests, :class_name => "SX1::Request", :primary_key =>

“pat_encounter_group”, :foreign_key => “req_encounter_group”
end
end

module SX1
class Request < RemoteSX1Model
set_table_name “request”
set_primary_key “req_reqno”
end
end

Thank you very much
Valentino

any idea?

Thanks

You didn’t say if it exists, but I’m guessing that there’s an
‘encounter group’ table associated to that number (99999). In which
case, what you’re looking at is a has_many :through relation.

(code example simplified - fix up with modules, etc as your app needs)

class Patient < ActiveRecord::Base

has field pat_encounter_group

belongs_to :encounter_group, :foreign_key => ‘pat_encounter_group’
has_many :requests, :through => :encounter_group
end

class EncounterGroup < ActiveRecord::Base
has_many :patients, :foreign_key => ‘pat_encounter_group’
has_many :requests, :foreign_key => ‘req_encounter_group’
end

class Request < ActiveRecord::Base
belongs_to :encounter_group, :foreign_key => ‘req_encounter_group’
has_many :patients, :through => :encounter_group
end

[Note: I haven’t tried this code, but it should work according to the
documentation]

On the other hand, the code you’ve got below should, in principle,
also work. How exactly did it “fail”?

–Matt J.

On Mar 17, 6:07 am, Valentino L. [email protected]