postgresql - 导轨 4 : Advanced Query for Search Interface

标签 postgresql ruby-on-rails-4 activerecord where-clause

我需要对我的模型执行查询,以允许我测试标签数组 (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/

相关文章:

ruby-on-rails - 测试 Controller 是否呈现 JS 模板

ruby-on-rails - rails 4 : Re-Migrating all Migrations to Schema

sql - Mysql 到 Rails SQL 查询

java - 使用 Postgres 和 Wicket 框架避免将重复的用户名插入数据库

javascript - 连接-pg-简单表达 : Failed to prune sessions: relation "session" does not exist. PostgreSQL

java - 我们如何从 postgresql 中的数据库函数将数据写入文件?

ruby-on-rails - 在rails 4中设计用户模型中保存自定义字段

ruby-on-rails - Ruby on Rails ActiveRecord 如何让 where 子句始终评估为真

activerecord - 在非 Rails 应用程序中测试 ActiveRecord 与 Shoulda 的关联

postgresql - Docker容器中的Postgresql版本与其数据不兼容