2. 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.
3. 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
4. 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.
5. 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
6. 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