简体   繁体   中英

Join Query on 2 tables(Rails 4)

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

Use this.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM