0

I having the following in my show.html.erb:

<% if @doctor.referrals_as_from.count > 0 %> 
  <% @doctor.referrals_as_from.each do |referral| %>
    <%= referral.to_id %>  
  <% end %>
<% end %> 

This works fine, giving me a list of matching id numbers from my referral model.

But, rather than getting a list of id numbers I would like to cross reference the "full_name" column from the Doctors model by using the identified id in referrals,basically an inner join. What is the most elegant way of doing this? Add a new method to the controller and to do a joins or includes, or is there a simpler way?

Models:

doctor.rb
class Doctor < ActiveRecord::Base
  self.primary_key = "npi"
  has_many :referrals_as_from, :class_name => 'Referral', :foreign_key => 'from_id'
  has_many :referrals_as_to, :class_name => 'Referral', :foreign_key => 'to_id'
end

referral.rb
class Referral < ActiveRecord::Base
  belongs_to :doctor
end
user2923767
  • 567
  • 1
  • 4
  • 13

2 Answers2

0

Use this.

<% if @doctor.referrals_as_from.count > 0 %> 
      <% @doctor.referrals_as_from.each do |referral| %>
        <%= referral.doctor.full_name  %>  
      <% end %>
<% end %> 
neo-code
  • 1,076
  • 10
  • 26
0

The Referral model actually has two doctors associated with it, as defined by to_id and from_id. So you might need to do the following:

referral.rb
class Referral < ActiveRecord::Base
  belongs_to :to_doctor, :class_name => "Doctor", :primary_key => "to_id", :foreign_key => "npi" 
  belongs_to :from_doctor, :class_name => "Doctor", :primary_key => "from_id", :foreign_key => "npi
end

Then the code becomes

referral.to_doctor.full_name
Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36