Forum: Ruby on Rails Has many association problem

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Valentino L. (Guest)
on 2009-03-17 12:07
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

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

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"

module SX1
  class Request < RemoteSX1Model
    set_table_name "request"
    set_primary_key "req_reqno"

Thank you very much
Valentino L. (Guest)
on 2009-03-18 05:04
any idea?

Matt J. (Guest)
on 2009-03-18 20:08
(Received via mailing list)
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

class EncounterGroup < ActiveRecord::Base
  has_many :patients, :foreign_key => 'pat_encounter_group'
  has_many :requests, :foreign_key => 'req_encounter_group'

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

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

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. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.