LoginSignup
9
9

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-07-19

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, 技術評論社.

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9