我正在尝试按标题制作搜索广告。
我的advertisements.rb
模型如下:
class Advertisement < ApplicationRecord
has_many :advertisement_tags, dependent: :destroy
has_many :comments
has_many :tags, through: :advertisement_tags
belongs_to :user
validates :title,
:description,
presence: true
def self.find_by_tags(tags)
Advertisement.joins(:tags).where('tags.tag_name IN (?)',
tags.split(/[\s,']/))
end
def self.find_by_titles(title)
if title
title_length = title.split.length
find(:all, conditions: [(['title LIKE ?'] * title_length).join(' AND ')] + title.split.map { |t| "%#{t}%" })
else
find(:all)
end
end
end
search_queries_controller.rb
:
class SearchQueriesController < ApplicationController
def search_by_tag
@advertisements = Advertisement.find_by_tags(tags_params)
render 'advertisements/index'
end
def search_by_title
@advertisements = Advertisement.find_by_titles(title_params)
render 'advertisements/index'
end
private
def tags_params
params.fetch(:tags, '')
end
def title_params
params.fetch(:title, '')
end
end
_search_title_form.html.slim
=form_tag search_by_title_path, method: :get do
=label_tag 'Type Title to Search:'
=text_field_tag :title
=submit_tag 'Search'
routes.rb
:
Rails.application.routes.draw do
root 'home#index'
resources :advertisements do
resources :comments, only: %i[new create delete]
end
resource :profile, only: %i[show edit update] do
get :your_advertisemnts, controller: :profiles, action: :index
end
devise_for :users, controllers: {
registrations: 'users/registrations'
}
get :search_by_tag, controller: :search_queries, action: :search_by_tag
get :search_by_title, controller: :search_queries, action: :search_by_title
end
我收到这些错误Couldn't find all Advertisements with 'id': (all, {:conditions=>["title LIKE ?", "%#{SOMETHING}%"]}) (found 0 results, but was looking for 2)
通过标签搜索工作正常,但它更简单,在这里我想通过标题中的任何单词找到广告。例如,标题&#39;每个人的好工作&#39;可以通过查询&#39;工作&#39;,好工作&#39;,&#39;每个人&#39;,工作为每个人&#39;等
答案 0 :(得分:0)
您使用的语法(find(:all, ...
)非常陈旧(在Rails 2中使用),并且当前版本的Rails不再支持。请改用where
:
def self.find_by_titles(title)
if title.present?
words = title.split(' ')
Advertisement.where(
Array.new(words.length, 'title LIKE ?').join(' AND '),
*words.map { |word| "%#{word}%" }
)
else
Advertisement.all
end
end