ransackの使い方
<参考>
Basic Search Using Ransack - RichOnRails.com
1.新規プロジェクト生成
$ rails new ransack_sample_app
$ cd ransack_sample_app
2.(Gemfile)に追加
gem 'ransack'
$ bundle install
3.モデルをgenerate
$ rails g model Product name
4.テストデータ生成
(db/seeds/rb)
Product.delete_all
Product.create!(name: 'Apples')
Product.create!(name: 'Oranges')
Product.create!(name: 'Strawberries')
Product.create!(name: 'Bananas')
Product.create!(name: 'Blueberries')
Product.create!(name: 'Pears')
Product.create!(name: 'Grapes')
5.Controllerをgenerate
$ rails g controller Products index
6.ルートを変更
(config/routes.rb)
Rails.application.routes.draw do
root to: 'products#index'
resources :products
end
7.Controllerの編集
(app/controllers/products_controller.rb)
class ProductsController < ApplicationController
def index
@q = Product.ransack(params[:q])
@products = @q.result
end
end
8.Viewの編集
(app/views/products/index.html.erb)
<h1>Products</h1>
<%= search_form_for @q do |f| %>
<%= f.label :name_cont %>
<%= f.search_field :name_cont %>
<%= f.submit %>
<% end %>
<table>
<thead>
<tr>
<th><%= sort_link(@q, :name) %></th>
</tr>
</thead>
<tbody>
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
</tr>
<% end %>
</tbody>
</table>
9.サーバーを立ち上げて確認
$ rails s