如何使用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
哦,很有趣,这解决了模棱两可的列问题。非常感谢!