noob question here. I have a has_many :through relationship between items and tags. Finding all items associated with a given tag is simple enough:
things=Tag.find(1).items
But what if I want to find all items associated with more than one given tag开发者_运维知识库? I was thinking something like:
things=Tag.find(1).items
Tag.find(2).things # wrong, but you get the idea
You can use the array union operator.
things = Tag.find(1).items | Tag.find(2).items
That will create an object for every item for both tags, which could be way too much depending on what you're trying to do. If you want something a little more scalable, you can do the lookup on the join table.
things = ItemTags.find_by_sql("
SELECT item_id, COUNT(tag_id) AS tag_count
FROM item_tags
WHERE tag_id IN (1, 2)
GROUP_BY item_id
HAVING tag_count = 2;
").map(&:item)
Just wrote that in browser, so it could be completely wrong. Also, there is probably a way to do that with activerecord finders that would be nicer that a find_by_sql.
things = Things.where(:tag => [1, 2])
things = Things.where('tag in :tags', [1, 2])
etc...
精彩评论