-
Notifications
You must be signed in to change notification settings - Fork 0
search model
Max Ivak edited this page Jul 7, 2015
·
4 revisions
controller:
search_filter :index, { search_url: :products_url } do
default_order "price", 'asc'
field :title, :string, :text, {label: 'Title', default_value: '', condition: :like_full}
field :price_from, :string, :text, {label: 'Price', default_value: '', condition: :custom, condition_where: 'price >= ?'}
field :price_to, :string, :text, {label: 'to', default_value: '', condition: :custom, condition_where: 'price <= ?'}
end
use options for a field in a filter:
condition: :custom, condition_scope: :myscope
'myscope' should be defined in your model.
Example. Search using custom scope
controller:
search_filter :index, {save_session: true, search_method: :post_and_redirect, search_url: :search_templates_url, search_action: :search} do
# define filter
default_order "title", 'asc'
# fields
field :title, :string, :text, {label: '', default_value: '', condition: :like_full}
field :parent_id, :int, :hidden, {label: '', default_value: 0, ignore_value: 0, condition: :custom, condition_scope: :of_parent}
end
def index
@items = Product.search_by_filter(@filter)
end
model:
searchable_by_simple_filter
scope :of_parent, lambda { |parent_id| where_parent(parent_id) }
def self.where_parent(parent_id)
if parent_id==0
where(_some_condition_)
elsif parent_id>0
where(_another_condition_)
end
end
Example. Autocomplete field with custom scope
define filter:
# controller
search_filter :index, {save_session: true, search_method: :post_and_redirect, url: :products_path, search_url: :search_products_path, search_action: :search} do
default_order "price", 'asc'
# autocomplete with custom scope
field :category, :string, :autocomplete, {label: 'Category', default_value: '', ignore_value: '', search_by: :id, source_query: :autocomplete_category_title_categories_path, condition: :custom, condition_scope: :of_category}
model:
class Product < ActiveRecord::Base
belongs_to :category
searchable_by_simple_filter
scope :of_category, lambda { |category_id| where_category(category_id) }
def self.where_category(id)
v = (id.to_i rescue 0)
if v>0
where(category_id: id)
else
where("1=1")
end
end
end
use options for a field in a filter:
condition: :custom,
condition_where: "parent_id = ?"
example: