【发布时间】: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 上的几个字段(即 title、subtitle 和 short_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