Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Advanced Techniques for Searchlogic 2
# your custom search
@search = Product.search(params[:search])
# searchlogic default
@search = Product.searchlogic(params[:search])
# app/models/product.rb
class Product < ActiveRecord::Base
scope_procedure :keywords, lambda { |query|
name_like_any(query.split(/\s+/))
}
end
# app/models/product_search.rb
class ProductSearch < Searchlogic::Search
def initialize(params, klass, current_scope)
# sanitize input params
allowed_params = [:item_number_equals, :keywords, :price_lte, :price_gte, :order]
conditions = {}
for x in allowed_params
conditions[x] = params[x] unless params[x].blank?
end
# call original initializer with sanitized conditions
super(klass, current_scope, conditions)
end
end
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def index
@search = Product.search(params[:search])
@products = @search.all
end
end
# search for "bucket"
Product.name_like_any("bucket")
# => SELECT * FROM `products` WHERE name LIKE "%bucket%"
# search for "plastic basket"
Product.name_like_any("plastic basket")
# => SELECT * FROM `products` WHERE name LIKE "%plastic basket%";
# what we intended
Product.name_like_any("plastic", "basket")
# => SELECT * FROM `products` WHERE name LIKE "%plastic%" OR name LIKE "%basket%";
<!-- app/views/products/index.html.erb -->
<% form_for @search do |f| %>
<ul>
<li>
<%= f.label :item_number_equals, "Item Number" %><br/>
<%= f.text_field :item_number_equals %>
</li>
<li>
<%= f.label :name_like_any, "Name" %><br/>
<%= f.text_field :name_like_any %>
</li>
<li>
<%= f.label :price_lte, "Price Min" %>
<%= f.text_field :price_lte, :size => 3 %> -
<%= f.label :price_gte, "Max" %>
<%= f.text_field :price_gte, :size => 3 %> -
</li>
</ul>
<% end %>
Product.keywords("plastic basket")
# => SELECT * FROM `products` WHERE name LIKE "%plastic%" OR name LIKE "%basket%";
<!-- app/views/products/index.html.erb -->
<!-- change this -->
<%= f.label :name_like_any, "Name" %><br/>
<%= f.text_field :name_like_any %>
<!-- to this -->
<%= f.label :keywords, "Keywords" %><br/>
<%= f.text_field :keywords %>
# app/models/product.rb
class Product < ActiveRecord::Base
scope_procedure :keywords, lambda { |query|
name_like_any(query.split(/\s+/))
}
# override Searchlogic::Search::Implementation
def self.search(params={})
ProductSearch.new(params || {}, self, scope(:find))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.