Edited at

ActiveModel::Modelで簡単に検索機能追加

More than 3 years have passed since last update.

Screenshot 2015-07-19 17.18.39.png


ActiveModel::Model

class SearchForm

include ActiveModel::Model

attr_accessor :q
end


Model


使用したModel関連Gems

gem 'pg',    '~> 0.17.1'  # PostgreSQLを使用するため


class Ingredient < ActiveRecord::Base

scope :sorted, ->{ order(name: :asc) }
scope :named, ->(q) { where("name ilike ?", "%#{q}%") }


View


使用したView関連Gems

gem "font-awesome-rails"  # fa_icon("アイコン名")を利用しアイコンを表示するため

gem 'haml-rails' # HAMLでテンプレートを書くため
gem 'bootstrap-sass' # Bootstrapを利用するため

.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"


Controller

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


参考資料

松田明、後藤大輔(2014)「詳解Rails 4」,『Ruby徹底攻略 (WEB+DB PRESS plus), p.89, 技術評論社.