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