這是可行嗎?鏈接導軌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
我希望能夠來鏈接這些關係在一起,以便(除其他原因),我可以用雷寶石的分頁這僅適用於關係不是數組 - 所以我需要返回一個範圍。
乾杯 - 這看起來很有幫助,並感謝識別問題...我會嘗試上述 –