(Rails3.2.13)
毎回、検索機能の実装する時、面倒だから便利ないい感じのプラグイン何かないかなと思ってたらあった。知らんかった。
『meta_search』使ってみる
下準備
$ rails new meta_search_app -T --skip-bundle $ cd meta_search_app
Gemfile
gem 'meta_search'
$ bundle install $ rails g scaffold Article title body:text published_at:datetime $ rake db:migrate
app/controllers/articles_controller.rb
def index @search = Article.search(params[:search]) @articles = @search.all
app/views/articles/index.html.erb
<h1>Listing articles</h1> <%= form_for(@search, :url => articles_path, :html => {:method => :get}) do |f| %> <%= f.label :title %> <%= f.text_field :title_contains %><br /> <%= f.label :body %> <%= f.text_field :body_contains %><br /> <%= f.label :published_at %> <%= f.datetime_select :published_at_greater_than, :include_blank => true %><br /> <%= f.submit %> <% end %> <table>
メモ
All data types
equals (alias: eq) - Just as it sounds.
does_not_equal (aliases: ne, noteq) - The opposite of equals, oddly enough.
in - Takes an array, matches on equality with any of the items in the array.
not_in (aliases: ni, notin) - Like above, but negated.
is_null - The column has an SQL NULL value.
is_not_null - The column contains anything but NULL.
Strings
contains (aliases: like, matches) - Substring match.
does_not_contain (aliases: nlike, nmatches) - Negative substring match.
starts_with (alias: sw) - Match strings beginning with the entered term.
does_not_start_with (alias: dnsw) - The opposite of above.
ends_with (alias: ew) - Match strings ending with the entered term.
does_not_end_with (alias: dnew) - Negative of above.
Numbers, dates, and times
greater_than (alias: gt) - Greater than.greater_than_or_equal_to (aliases: gte, gteq) - Greater than or equal to.
less_than (alias: lt) - Less than.
less_than_or_equal_to (aliases: lte, lteq) - Less than or equal to.
Booleans
is_true - Is true. Useful for a checkbox like "only show admin users".
is_false - The complement of is_true.
Non-boolean data types
is_present - As with is_true, useful with a checkbox. Not NULL or the empty string.is_blank - Returns records with a value of NULL or the empty string in the column.
activerecord-hackery/meta_search · GitHub