gpt4 book ai didi

ruby-on-rails - 我如何在 Rails 中搜索类别名称?

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:26 24 4
gpt4 key购买 nike

我的工作模型中有一个搜索功能,如果我想搜索工作的标题或描述,它可以正常工作

def self.search(search)

if search
where(["title LIKE ? OR description LIKE ?", "%#{search}%" , "%#{search}%"])
else

end

end

如何按类别名称搜索?我只能弄清楚按 category_id 搜索类别并在搜索表单中输入数字。

def self.search(search)

if search
where(["title LIKE ? OR category_id LIKE ?", "%#{search}%" , "%#{search}%"])
else

end

end

我的模式

create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

create_table "jobs", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "company"
t.string "url"
t.integer "user_id"
t.integer "city_id"
t.integer "category_id"
t.string "phone"
t.string "slug"
end

我的工作 Controller

def search
@jobs = Job.search(params[:search])
end

最佳答案

您需要包含一个 joins 语句,表示您在查询中包含了 CATEGORIES 表。

此外,如果搜索是一个字符串,则不需要使用字符串注入(inject)将其转换为字符串。

def self.search(search)
joins(:category).where(
["categories.name like ? OR title LIKE ? OR description LIKE ?",
search, search, search]
)
end

请注意,joins 语句使用关系的名称。我假设您在 Job 类中有这样一行:

belongs_to :category

并且在SQL片段中,需要使用表的名称,categories。

关于ruby-on-rails - 我如何在 Rails 中搜索类别名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49386742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com