I'm not sure how to better ask this question.
I have model Item
and model Tag
, assotiation has_and_belongs_to_many
I need to get result from table items_tags
which contains item_id's that have records with 2 tags. Example:
Here I need item_id which tag_id both in 1 and 2. (result: item_id=4)
So if I use WHERE tag_id = 1 AND tag_id = 2
- there are no results.
If WHERE tag_id IN (1,2)
- too many results (red and green)
I can follow the next steps:
1) first = tag1.items.pluck(:id)
2) second = tag2.items.pluck(:id)
3) what_i_need = (first & second)
Another way is one query: tag1.items.where(id: tag2.products.pluck(:id))
Is there is another (more faster) way to do it with some variant of JOIN?