Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用SQL ILIKE搜索查询ActiveRecord关联(.join)_Sql_Ruby On Rails_Postgresql - Fatal编程技术网

如何使用SQL ILIKE搜索查询ActiveRecord关联(.join)

如何使用SQL ILIKE搜索查询ActiveRecord关联(.join),sql,ruby-on-rails,postgresql,Sql,Ruby On Rails,Postgresql,我试图通过将查询参数传递给控制器来查询多个活动记录模型。在我的tales\u controller.rb中,我有以下索引方法: def index @tales_count = Tale.all.count if params[:search] @tales = Tale.joins(:category) .where('category.title ILIKE ?', "%#{params[:search]}%")

我试图通过将查询参数传递给控制器来查询多个活动记录模型。在我的
tales\u 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”是不明确的
。我感觉这是因为我试图查询故事以及类别模型上的标题字段。但是,我自己无法解决这个问题

通过为索引方法提供正确的查询,我希望能够查询故事模型上的几个字段(即
title
subtitle
short\u description
以及可能更多),以及类别模型上的
title
-字段

类别模型由故事模型引用。这就是
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
和任何其他故事字段都包含搜索词。坦白说,这不是我想要的。

Rails中的表名按惯例是复数形式。所以把这个改为

.where('categories.title ILIKE ?', "%#{params[:search]}%")
只是为了好玩,我喜欢Postgres中的

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

在第二个
where
子句中,
tales.title=…
没有帮助吗?不幸的是,没有,我尝试了将表的名称也命名为
category
?就像这一行中的
.where('category.title
哦,很有趣,这解决了
模棱两可的列问题。非常感谢!