[英]ruby rails activerecord nested select
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.
例如,查找所有具有tag.id == 5,tag.id == 6和tag.id == 7的记录。 (although, that could be 2 tag ids, or 2000 tag ids)
(尽管可能是2个标签ID或2000个标签ID)
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. 我试图通过对数据库的查询来做到这一点,以便它快速而不是带回一个大集合并用ruby减少它。
The SQL query would like something like this, I think: 我认为SQL查询需要这样的东西:
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'
)
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). 我认为这应该有效(不过,我不确定它是否可以在
:through
关联上使用)。 Give it a try. 试试看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.