找不到所有带有"id"的广告:(全部,{:条件=>[ "title LIKE ?" , "%#{SOMETHING}%" ]})(找到 0 个结果,但正在寻找 2 个)



我正在尝试按标题制作搜索广告。 我的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)按标签搜索工作正常,但它更简单,在这里我想通过其标题中的任何单词找到广告。例如,标题"适合所有人的好工作"可以通过查询"工作"、"好工作"、"每个人"、"每个人的工作"等找到。

您使用的语法(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

相关内容

最新更新