Abdul Baig
Abdul Baig

Reputation: 3721

how to get records using join between tables

i have doctors table and a users table such that user belongs_to doctor and doctor has_one user as profile. (polymorphic relation)

i want data from doctors table as well as users table where doctor.id = users.profile_id

@search_query =  params[:doctor][:query]
@users = User.select("profile_id, username").where("username like ? OR address like ?", @search_query, @search_query )
@doctor = Doctor.select("doctors.start_time, doctors.end_time, doctors.detail, doctors.experience, doctors.license_number, doctors.fee, doctors.available_days, doctors.specialization, doctors.mission_statement, doctors.id, users.id AS user_id, users.name, users.email, users.username, users.address, users.age, users.gender").joins(:user).where("? = doctors.id", @users.each do |u| u.profile_id end)#.joins(:user).where(:users => {:users.profile_id => @doctor.id})

Doctors' migration

 create_table(:users) do |t|
  ## Database authenticatable
  t.string :email,              :null => false, :default => ""
  t.string :encrypted_password, :null => false, :default => ""
  t.string :username, :null => false
  t.string :address
  t.integer :age
  t.string :gender
  t.string :name
  t.integer :profile_id
  t.string :profile_type

Users' migration

class CreateDoctors < ActiveRecord::Migration
  def change
    create_table :doctors do |t|
      t.time :start_time
      t.time :end_time
      t.text :detail
      t.integer :experience
      t.text :mission_statement
      t.string :license_number
      t.integer :fee
      t.string :available_days
      t.string :specialization

      t.timestamps
    end
  end
end

Upvotes: 0

Views: 109

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Doctor.joins("LEFT OUTER JOIN users ON doctors.id = users.profile_id")

Upvotes: 1

Related Questions