简体   繁体   English

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

[英]How do i search category name in Rails?

I have a search function in my job model that works fine if i want to search the title or description for jobs 我的工作模型中有一个搜索功能,如果我想搜索职位的标题或说明,该功能就可以正常工作

def self.search(search)

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

    end

end

how do i search by category name? 如何按类别名称搜索? i can only figure out to search categories by category_id and entering the number in the search form. 我只能找出通过category_id搜索类别并在搜索表单中输入数字。

def self.search(search)

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

        end

    end

my schema 我的图式

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

My jobs controller 我的工作控制器

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

You need to include a joins statement, to say you're including the CATEGORIES table in your query. 您需要包括一个joins语句,以表示您要在查询中包括CATEGORIES表。

Also, if search is a string, you don't need to convert it to a string by using string injection. 此外,如果搜索是字符串,则无需使用字符串注入将其转换为字符串。

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

Note that the joins statement uses the name of the relationship. 请注意, joins语句使用关系的名称。 I'm assuming you have a line like this in the Job class: 我假设您在Job类中有这样一行:

belongs_to :category

And in the SQL fragment, you need to use the name of the table, categories. 在SQL片段中,您需要使用表的名称,类别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM