user2954587
user2954587

Reputation: 4861

Rails 5 joins filter associated

How can I use a joins to query an associated model in rails 5? What I've tried is DoctorLocation.joins(:location).where(:location => {:confidence => 2}) after looking at the documentation and this question. What am I doing wrong? My query isn't returning any results.

pry(main)> DoctorLocation.joins(:locations).where(:locations => {:confidence => 2})
=> #<DoctorLocation::ActiveRecord_Relation:0x3ff735a09d8c>

class DoctorLocation
   belongs_to :location

end

class Location
   has_many :doctor_locations, dependent: :destroy

end

Migration

   create_table :doctor_locations do |t|
      t.integer :doctor_profile_id
      t.integer :location_id
      t.text :uuid
      t.timestamps null: false
    end


 create_table :locations do |t|
      t.string   :address
      t.integer  :ordinal, :default => 1
      t.integer  :doctor_profile_id
      t.text     :uuid
      t.timestamps
    end

 add_column :locations, :confidence, :integer

Upvotes: 0

Views: 422

Answers (2)

max
max

Reputation: 102046

You actually have the right query. Rather its your testing method that is broken.

class DoctorLocation < ApplicationRecord
  belongs_to :location
  def self.with_confidence(c)
    DoctorLocation.joins(:location).where(locations: { confidence: c })
  end
end

This passing spec confirms that it works as expected:

require 'rails_helper'

RSpec.describe DoctorLocation, type: :model do

  after(:each) { DoctorLocation.destroy_all }
  it "includes locations with the correct confidence" do
    dl = DoctorLocation.create!(location: Location.create!(confidence: 2))
    DoctorLocation.create!(location: Location.create!(confidence: 1))
    expect(DoctorLocation.with_confidence(2)).to include dl
    expect(DoctorLocation.with_confidence(2).count).to eq 1
  end
  it "does not include rows without a match in the join table" do
    dl = DoctorLocation.create!(location: Location.create!(confidence: 1))
    expect(DoctorLocation.with_confidence(2)).to_not include dl
  end
end

Upvotes: 1

Ilya Konyukhov
Ilya Konyukhov

Reputation: 2791

In joins and where (hashed arguments) you need to declare name of association (location), not table name (locations):

DoctorLocation.joins(:location).where(location: { confidence: 2 })

It's often a source of confusion.

Upvotes: 0

Related Questions