Skip to content

Instantly share code, notes, and snippets.

@mnishiguchi
Last active September 7, 2015 19:32
Show Gist options
  • Save mnishiguchi/4aa45a58956bd7183cb5 to your computer and use it in GitHub Desktop.
Save mnishiguchi/4aa45a58956bd7183cb5 to your computer and use it in GitHub Desktop.
ActiveModel::Modelで簡単に検索機能追加 ref: http://qiita.com/mnishiguchi/items/4681bb16f440d6032eaf
class SearchForm
include ActiveModel::Model
attr_accessor :q
end
class Ingredient < ActiveRecord::Base
scope :sorted, ->{ order(name: :asc) }
scope :named, ->(q) { where("name ilike ?", "%#{q}%") }
class Ingredient < ActiveRecord::Base
scope :sorted, ->{ order(name: :asc) }
scope :named, ->(q) { where("name ilike ?", "%#{q}%") }
class IngredientsController < ApplicationController
before_action :search_ingredients, only: :index
def index
end
def search_ingredients
@search = SearchForm.new(params[:search_form])
@ingredients = if @search.q.present?
then Ingredient.all.named(@search.q)
else Ingredient.all
end.sorted
end
.filter_wrapper{ style: "margin-bottom: 20px;" }
= form_for @search, url: ingredients_path, html: {method: :get}, class: "form-horizontal" do |f|
.form-group
.input-group
= f.search_field :q, class: "form-control"
%span.input-group-btn
= f.button fa_icon("search"), class: "btn btn-default"
class IngredientsController < ApplicationController
before_action :search_ingredients, only: :index
def index
end
private
def search_ingredients
@search = SearchForm.new(params[:search_form])
@ingredients = if @search.q.present?
then Ingredient.all.named(@search.q)
else Ingredient.all
end.sorted
end
end
gem 'pg', '~> 0.17.1' # PostgreSQLを使用するため
gem "font-awesome-rails" # fa_icon("アイコン名")を利用しアイコンを表示するため
gem 'haml-rails' # HAMLでテンプレートを書くため
gem 'bootstrap-sass' # Bootstrapを利用するため
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment