Upload
framgia-vietnam
View
2.429
Download
2
Embed Size (px)
Citation preview
Ruby on rails
RanSack
Design by Mr.Huân
What's Ransack
Ransack is a rewrite of MetaSearch. While it supports many of the same features as MetaSearch, its underlying implementation differs greatly from MetaSearch, and backwards compatibility is not a design goal.
Ransack enables the creation of both simple and advanced search forms against your application's models.
Basic Searching
• Eq :The eq predicate returns all records where a field is exactly equal to a given value.
>> Product.search(:name_eq => "Flux Capacitor").result.to_sql
=> "SELECT \"products\".* FROM \"products\" WHERE \"products\".\"name\" = 'Flux Capacitor'"
• Matches
• lt
• In
• Cont
• Start
• End
Usage ransack
Ransack can be used in one of two modes:
•Simple Mode
• The default param key for search params is now :q, instead of :search.
• form_for is now search_form_for and validates that a Ransack::Search object is passed to it.
• Common ActiveRecord::Relation methods are no longer delegated by the search object. Instead, you will get your search results via a call to Search#result.
Simple Mode(continue)
In your controller:
def index
@q = Person.search(params[:q])
@people = @q.result(:distinct => true)
end
In your view:<%= search_form_for @q do |f| %>
<%= f.label :name_cont %> <%= f.text_field :name_cont %>
<%= f.label :articles_title_start %> <%= f.text_field :articles_title_start %> <%= f.submit %>
<% end %>
//View list Products
Advanced Search
• "Advanced" searches (ab)use Rails' nested attributes functionality in order to generate complex queries with nested AND/OR groupings, etc. A notable drawback with these searches is that the increased size of the parameter string will typically force you to use the HTTP POST method instead of GET.
• routes...
resources :products do
collection { post :search, to: 'products#index' }
end
end
Advanced Search(Continue)
• controller action ...
def search
index
render :index
end
• search_form_for line in the view ...
<%= search_form_for @q, :url => search_products_path,
:html => {:method => :post} do |f| %>
has_many and belongs_to associations
Can easily use Ransack to search in associated objects.
Model:
class Product < ActiveRecord::Base
belongs_to :Category
end
class Category < ActiveRecord::Base
has_many :Products
end
class ProductsController < ApplicationController
def index
@search = Product.search(params[:q]
@Products = @search.result(:distinct => true)
end
end
Form…
<%= search_form_for @search do |f| %>
<%= f.label :name_cont %> <%= f.text_field :name_cont %>
<%= f.label :category_name_cont %> <%= f.text_field :categoris_last_name_cont %>
<%= f.submit "search" %>
<% end %>
Thank for watching