Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.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
Ruby on rails 如何在Rails中搜索类别名称?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 如何在Rails中搜索类别名称?

Ruby on rails 如何在Rails中搜索类别名称?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我在我的工作模型中有一个搜索功能,如果我想搜索工作的标题或描述,它可以很好地工作 def self.search(search) if search where(["title LIKE ? OR description LIKE ?", "%#{search}%" , "%#{search}%"]) else end end 如何按类别名称进行搜索?我只能通过category_id和在搜索表单中输入数字来确定搜索类别 def self.searc

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

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
我的作业管理员

def search
    @jobs = Job.search(params[:search])
end
您需要包含一个JOIN语句,表示您正在查询中包含CATEGORIES表

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

def self.search(search)
  joins(:category).where(
    ["categories.name like ? OR title LIKE ? OR description LIKE ?",
     search, search, search]
  )
end
请注意,joins语句使用关系的名称。我假设你在职业课上有这样一句话:

belongs_to :category

在SQL片段中,您需要使用表名categories。

只是好奇,您使用的是哪个数据库?我不完全确定这种语法是否适用于所有这些语法。我正在使用postgresql