【问题标题】:How to search-query ActiveRecord Associations (.joins) with SQL ILIKE如何使用 SQL ILIKE 搜索查询 ActiveRecord 关联 (.joins)
【发布时间】:2019-04-25 18:52:22
【问题描述】:

我正在尝试通过将查询参数传递给控制器​​来查询多个活动记录模型。在我的tales_controller.rb 中,我有以下索引方法:

def index
  @tales_count = Tale.all.count

  if params[:search]
    @tales = Tale.joins(:category)
                 .where('category.title ILIKE ?', "%#{params[:search]}%")
                 .where(
                   'title ILIKE :search OR
                   subtitle ILIKE :search OR
                   short_description ILIKE :search', search: "%#{params[:search]}%"
                  )
  else
    @tales = Tale.all
  end

  render template: 'tales/index'
end

现在,我似乎无法弄清楚这个问题的正确解决方案,因为大部分PG都会抛出错误,说:PG::AmbiguousColumn: ERROR: column reference "title" is ambiguous。我感觉这是因为我尝试在 Tale- 以及 Category-Model 上查询标题字段。但是我自己无法解决这个问题。

通过为索引方法提供正确的查询,我希望能够查询 Tale-Model 上的几个字段(即 titlesubtitleshort_description 以及可能更多),以及类别模型上的title-字段。

Category-Model 被 Tale-Model 引用。这就是schema.rb 的样子:

create_table "tales", force: :cascade do |t|
  t.string "public_id"
  t.string "title"
  t.string "subtitle"
  t.string "player_count"
  t.string "short_description"
  t.datetime "published_at"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.bigint "category_id"
  t.bigint "author_id"
  t.index ["author_id"], name: "index_tales_on_author_id"
  t.index ["category_id"], name: "index_tales_on_category_id"
end

编辑:嗯,我刚刚意识到,通过查询我目前的方式,我希望 category.title 和任何其他故事字段都带有搜索词。坦率地说,这不是我想要的。

【问题讨论】:

  • tales.title = ... 在第二个where 子句中没有帮助吗?
  • 很遗憾没有,我也试过了
  • 表名category不是categories吗?如这一行.where('category.title
  • 哦,有趣,这解决了ambiguous column 问题。非常感谢!

标签: sql ruby-on-rails postgresql


【解决方案1】:

Rails 中的表名按惯例采用复数形式。所以把它改成阅读

.where('categories.title ILIKE ?', "%#{params[:search]}%")

为了好玩,Postgres 中的ILIKE 可以写成

.where('categories.title ~* ?', params[:search]) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2010-10-15
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多