rails
gem
ransack
ransack を使ったときのメモ
ransack とは
- 検索フォームを簡単に作れるGem。
参考URL
Install
gem 'ransack'
gem 'ransack', github: 'activerecord-hackery/ransack'
Usage
README の書き方
-
Controller
def index @q = Person.ransack(params[:q]) @people = @q.result(distinct: true) end
-
View
= search_form_for @q do |f| = f.label :name_cont = f.search_field :name_cont = f.label :articles_title_start = f.search_field :articles_title_start = f.label :name_or_description_or_email_or_articles_title_cont = f.search_field :name_or_description_or_email_or_articles_title_cont = f.submit
Snippets
Controller
-
kaminari
と一緒に使う場合 (次のコードのようにresult
に続けてpage
やper
などkaminari
のメソッドを使えば良い)def index @q = Item.ransack(params[:q]) @items = @q.result .page(params[:page]) .per(10) end
View
-
README の書き方
<%= search_form_for @q do |f| %> # Search if the name field contains... <%= f.label :name_cont %> <%= f.search_field :name_cont %> # Search if an associated articles.title starts with... <%= f.label :articles_title_start %> <%= f.search_field :articles_title_start %> # Attributes may be chained. Search multiple attributes for one value... <%= f.label :name_or_description_or_email_or_articles_title_cont %> <%= f.search_field :name_or_description_or_email_or_articles_title_cont %> <%= f.submit %> <% end %>
-
Bootstrap3 と一緒に使う場合
= search_form_for @q do |f| .form-group = f.label :name_cont, {class: 'control-label'} = f.search_field :name_cont, {class: 'form-control'} .form-group = f.label :articles_title_start, {class: 'control-label'} = f.search_field :articles_title_start, {class: 'form-control'} .form-group = f.label :name_or_description_or_email_or_articles_title_cont, {class: 'control-label'} = f.search_field :name_or_description_or_email_or_articles_title_cont, {class: 'form-control'} .form-group = f.submit class: 'btn btn-primary btn-block'
-
検索条件にセレクトボックス(
collection_select
)と一緒に使う場合= f.select \ :item_id_eq, \ content_tag(:option,'Select one ...', value: "") + \ options_from_collection_for_select(item.all, :id, :name, @q.item_id_eq)
-
スタイルを指定する場合
= f.search_field :logged_at_cont, {class: 'form-control'} = f.select :item_id_eq, \ content_tag(:option,'',value: "") + \ options_from_collection_for_select(@items, :id, :name, @q.item_id_eq), \ {}, {class: 'form-control'}