我需要对我的模型执行查询,以允许我测试标签数组 (belongs_to :recipe
)
class Recipe < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
end
class Tag < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :recipes, through: :taggings
end
当我这样做时它会起作用:
Recipe.joins(:tags).where("tags.name = ?", 'main course')
但我想测试一组标签。如果我不使用 join
,我可以使用数组进行查询,如下所示:
Recipe.where(id: [1, 2, 3])
但是当我尝试时它失败了:
Recipe.joins(:tags).where(tags.name: ['main course', 'snack'])
如何修复最终查询 (postgres db) 以允许使用数组?
最佳答案
Recipe.where(id: [1, 2, 3])
将使用 in
因为传递了 id 数组。
要使其与 tags.name 一起使用,
Recipe.joins(:tags).where('tags.name in (?) ', ['main course', 'snack'])
应该在我们从连接关系而不是食谱表中搜索时使用。
关于postgresql - 导轨 4 : Advanced Query for Search Interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41488410/