A4J
A4J

Reputation: 889

Rails .joins query over multiple associations

I have this query that works as expected:

@dog.listings.joins(:address_country).merge(Country.where(permalink: 'uk'))

This query gives me the Listings where the country matches 'uk' (Listing has_one :address_country, which is a country from the Country model)

But when I add another association to the chain in between cat and listing (litter), it doesn't work (a litter belongs to a listing, as well as to a cat):

@dog.litters.joins(:listing) & Listing.joins(:address_country) & Country.where(permalink: 'uk')

In this query I'd like it to fetch the Litters where the country (of the associated listing) matches. But it just returns an empty array. The first query works, and I guess I just need to bolt that on to @cat.litters?)

In Rails C, I'm getting this:

 d.litters.joins(:listing) & Listing.joins(:address_country).merge(Country.where(permalink: 'uk'))

  Litter Load (0.6ms)  SELECT "litters".* FROM "litters" INNER JOIN "listings" ON "listings"."id" = "litters"."listing_id" WHERE "litters"."litterable_id" = 11 AND "litters"."litterable_type" = 'Dog'
  Listing Load (0.4ms)  SELECT "listings".* FROM "listings" INNER JOIN "countries" ON "countries"."id" = "listings"."address_country_id" WHERE "countries"."permalink" = 'uk'
=> []

Any ideas what I'm doing wrong?

Upvotes: 0

Views: 1508

Answers (1)

Jiří Pospíšil
Jiří Pospíšil

Reputation: 14401

One thing that's definitely wrong is to assume that & is the same as merge. It used to be but was removed in fbd917 - now it's just ruby's array intersection and that's not what you want.

I am not sure I follow the database schema from the brief description you gave but just rewriting it to merge is worth the shot:

@dog.litters.joins(:listing).merge(Listing.joins(:address_country)).merge(Country.where(permalink: 'uk'))

and again without actually running the code I would guess that this is equivalent:

@dog.litters.joins(listing: :address_country).where(countries: {permalink: "uk"})

Upvotes: 1

Related Questions