简体   繁体   中英

Rails extract values with join associations

I have a rails join table between 2 models superhero and superpower . Now I have 3 different superpower id and I want all the superheroes which have all the selected superpowers

To do that I'm trying to do the following:

matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id = ?', 17).where('superpowers.id = ?', 12).where('superpowers.id = ?', 6)

But this gives me an empty object even though I have superheroes which have all the given superpowers in my join table

The query generated from the above is:

SELECT "superheroes".* FROM "superheroes" INNER JOIN "superheroes_superpowers" ON "superheroes_superpowers"."superhero_id" = "superheroes"."id" INNER JOIN "superpowers" ON "superpowers"."id" = "superheroes_superpowers"."superpower_id" WHERE (superpowers.id = 17) AND (superpowers.id = 17) AND (superpowers.id = 12) AND (superpowers.id = 6)

So weirdly it tries to check for the superpower with id 17 twice (but it shouldn't affect the result I think) and the rest of the query seems to be correct.

try using an in clause

superpowers_ids = [17,12,6]
matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id in (?)', superpowers_ids)
Superhero.joins(:superpowers).where(superpowers:  { id: [17,12,6] } )

This gives the following SQL query (formatted for readibility):

SELECT "superheros".* 
FROM "superheros" 
INNER JOIN "superhero_superpowers" ON "superhero_superpowers"."superhero_id" = "superheros"."id" 
INNER JOIN "superpowers" ON "superpowers"."id" = "superhero_superpowers"."superpower_id" 
WHERE "superpowers"."id" IN (17, 12, 6)

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