这是可行吗?链接导轨3通过关联has_many范围3
我有以下范围:
class Thing < ActiveRecord::Base
scope :with_tag, lambda{ |tag| joins(:tags).where('tags.name = ?', tag.name)
.group('things.id') }
def withtag_search(tags)
tags.inject(scoped) do |tagged_things, tag|
tagged_things.with_tag(tag)
end
end
我得到一个结果,如果有与Thing.withtag_search(array_of_tags)
通过在标签阵列中的一个标签,但如果我是数组中传递多个标签我得到一个空的关系作为结果。在情况下,它可以帮助:
Thing.withtag_search(["test_tag_1", "test_tag_2"])
SELECT "things".*
FROM "things"
INNER JOIN "things_tags" ON "things_tags"."thing_id" = "things"."id"
INNER JOIN "tags" ON "tags"."id" = "things_tags"."tag_id"
WHERE (tags.name = 'test_tag_1') AND (tags.name = 'test_tag_2')
GROUP BY things.id
=> [] # class is ActiveRecord::Relation
而
Thing.withtag_search(["test_tag_1"])
SELECT "things".*
FROM "things"
INNER JOIN "things_tags" ON "things_tags"."thing_id" = "things"."id"
INNER JOIN "tags" ON "tags"."id" = "things_tags"."tag_id"
WHERE (tags.name = 'test_tag_1')
GROUP BY things.id
=> [<Thing id:1, ... >, <Thing id:2, ... >] # Relation including correctly all
# Things with that tag
我希望能够来链接这些关系在一起,以便(除其他原因),我可以用雷宝石的分页这仅适用于关系不是数组 - 所以我需要返回一个范围。
干杯 - 这看起来很有帮助,并感谢识别问题...我会尝试上述 –