Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What is going on with this article?
@mnishiguchi

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

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

10
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
mnishiguchi
Software Engineer in Washington DC

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
10
Help us understand the problem. What is going on with this article?