Last active
August 29, 2015 14:25
-
-
Save mnishiguchi/821648ff724aac1d176c to your computer and use it in GitHub Desktop.
pg_searchで簡単に検索機能追加 ref: http://qiita.com/mnishiguchi/items/02d96cdc8575d268a937
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IngredientsController < ApplicationController | |
before_action :search_ingredients, only: :index # indexアクションのみ | |
def index | |
end | |
... | |
private | |
def ingredient_params | |
params.require(:ingredient).permit(:name, :volume) | |
end | |
# 検索用パラメータの有無を検知。検索用パラメータがある場合のみ検索処理。 | |
def search_ingredients | |
@ingredients = if params[:search].present? | |
then Ingredient.search(params[:search]) | |
else Ingredient.all | |
end.sorted.paginate(page: params[:page]) | |
end | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ruby 2.2.1 | |
gem 'rails', '~> 4.2.1' | |
gem 'pg', '~> 0.17.1' | |
gem 'pg_search', '~> 1.0.3' # Named scopes that take advantage of PostgreSQL's full text search | |
gem 'haml-rails', '~> 0.9.0' | |
gem 'bootstrap-sass', '~> 3.2.0.0' # Converts Less to Sass. | |
# etc |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ingredient < ActiveRecord::Base | |
include PgSearch # 忘れずincludeすること。 | |
scope :sorted, ->{ order(name: :asc) } | |
pg_search_scope :search, | |
against: [ | |
:name, | |
:volume | |
], | |
using: { | |
tsearch: { | |
prefix: true, | |
normalization: 2 | |
} | |
} | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
# 検索機能 | |
.filter_wrapper{ style: "margin-bottom: 20px;" } | |
= form_tag(ingredients_path, method: "get") do | |
= text_field_tag :search, nil, placeholder: "Search ingredients ...", class: "form-control" | |
= submit_tag "", style: "display: none;" | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment