Eric
Eric

Reputation: 793

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.

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

Upvotes: 2

Views: 470

Answers (1)

AJFaraday
AJFaraday

Reputation: 2450

You need to include a joins statement, to say you're including the CATEGORIES table in your query.

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. I'm assuming you have a line like this in the Job class:

belongs_to :category

And in the SQL fragment, you need to use the name of the table, categories.

Upvotes: 4

Related Questions