逗号分隔字符串与高级搜索

时间:2015-02-19 17:12:52

标签: sql ruby search ruby-on-rails-4 tagging

我已使用此tutorial向我的图书应用添加了高级搜索。一切正常,但现在我试图通过其标签找到一本书。

如果用户在:keywords text_field中输入一个Tag,我就会进行高级搜索。

有没有办法通过用逗号分割关键字字符串来搜索各种标签?

(ex: fun, kid stories, action) 
Would allow me to search books with fun OR kids stories OR actions.

如何通过逗号分隔的字符串搜索多个标记?

注意:我创建了一个我认为可以提供帮助的搜索方法,但我不确定如何将其与单个关键字搜索相结合。

MODEL

class Book < ActiveRecord::Base

  has_many :book_mappings
  has_many :tags, through: :book_mappings

end


class BookMapping < ActiveRecord::Base
  belongs_to :book
  belongs_to :tag
end

class Tag < ActiveRecord::Base

  has_many :book_mappings
  has_many :books, through: :book_mappings

end


class Search < ActiveRecord::Base

  def books
    @books ||= find_books
  end

  def find_books
    books = Book.order(:name)

    ###This works for a single word but NOT if I have multiple tags separated by commas
    books = books.joins(:tags).where("tags.name like ?", "%#{keywords}%") if keywords.present?

    books
  end

  def search(keywords)
     return [] if keywords.blank?
     cond_text = keywords.split(', ').map{|w| "name LIKE ? "}.join(" OR ")    
     cond_values = keywords.split(', ').map{|w| "%#{w}%"}
     all(:conditions =>  (keywords ? [cond_text, *cond_values] : []))
  end

end

视图

<%= form_for @search do |f| %>

  <div class="field">
    <%= f.label :keywords %><br />
    <%= f.text_field :keywords %>
  </div>

<% end %>

1 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案。只需为每个关键字添加like语句。

过滤包含所有标记的图书

if keywords.present?
  books = books.joins(:tags)
  keywords.tr(' ','').split(',').each do |keyword|
    books = books.where("tags.name like ?", "%#{keyword}%") 
  end
end

使用任何标记过滤图书

if keywords.present?
  books = books.joins(:tags)

  keyword_names = keywords.split(', ')
  cond_text = keyword_names.map{|w| "tags.name like ?"}.join(" OR ")
  cond_values = keyword_names.map{|w| "%#{w}%"}

  books = books.where(cond_text, *cond_values)
end