2017-07-27 21 views
0

我想按标题进行搜索广告。 我advertisements.rb模式是这样的:找不到所有带'id'的广告:(all,{:conditions => [“title LIKE?”,“%#{SOMETHING}%”]})(找到0个结果,但正在寻找2)

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

+1

'找到(:所有...'是一个非常古老的语法运行Rails中查询并不在新版本中继续工作,但是,你的其他代码看起来并不像它。是针对一个老的Rails版本实现的,你使用什么版本的Rails? – spickermann

+0

@spickermann我正在使用'rails 5.1.2' –

+0

@spickermann,想我想要 –

回答

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 
+0

谢谢!这是一个答案! –