1

I have three tables/models.

Recordings (id)
has_many :hits
has_many :tags, :through => :hits

Hits (id, recording_id, tag_id)
belongs_to :recordings
belongs_to :tags

Tags (id)
has_many :hits
has_many :recordings, :through => :hits

I need to find all recordings that have all the tags that are passed in as a parameter. For example, find all recordings that have tag.id == 5, tag.id == 6, and tag.id ==7. (although, that could be 2 tag ids, or 2000 tag ids)

I'm trying to do this with a query to the db so that it's fast instead of bringing back a large set and reducing it with ruby.

The SQL query would like something like this, I think:

SELECT * FROM recordings 
WHERE id IN (
  SELECT recording_id FROM hits 
  WHERE recording_id IN (
    SELECT recording_id FROM hits 
    WHERE recording_id IN (
      SELECT recording_id from hits WHERE recording_id = 5
    )
    AND tag_id = '6'
  ) 
  AND tag_id == '7'
)

1 Answer 1

1
Recording.joins(:tags).where(:tags => { :id => [5,6,7] })

I think this should work (I'm not sure it will on the :through association, though). Give it a try.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you'd need to join hits as well: .joins(:hits => :tags)
Going to try, but i think that will do an or instead of an and. (all recordings wher tag_id is 5 or 6 or 7)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.