LoginSignup
4
2

More than 5 years have passed since last update.

[Ruby/Rails]Gemを利用せずに検索機能を実装する方法

Last updated at Posted at 2018-01-15

Gemを利用せずに検索機能を実装する方法

スクリーンショット 2018-01-15 11.35.08.png

共有すること

Railsで開発したWEBアプリに、Gemを利用せずコードを数行入力して検索機能を実装する。

開発環境

Ruby 2.4.1
Rails 5.1.4

前提条件

下記コマンドを実行して、sampleアプリを作成する。

command
rails new sample
cd sample
rails g scaffold Product name:string
rails db:migrate

アプリ名:sample
モデル名:Product

カラム
name String

コード

今回作成したコード:https://github.com/tanakadaichi1989/search

モデル

product.rb
class Product < ApplicationRecord
  def self.search(search)
    if search
      Product.where(Product.arel_table[:name].matches("%#{search}%"))
    else
      Product.all
    end
  end
end

コントローラ

products_controller.rb
class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  # GET /products
  # GET /products.json
  def index
    @products = Product.search(params[:search])
  end

  #...(省略)...
end

ビュー

index.html.erb
<p id="notice"><%= notice %></p>

<h1>Products</h1>

<!-- 追加したコード ここから -->
<%= form_tag("/products",method:"get") do %>
<input type="text" name="search">
<input type="submit" value="search">
<% end %>
<!-- 追加したコード ここまで -->

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= link_to 'Show', product %></td>
        <td><%= link_to 'Edit', edit_product_path(product) %></td>
        <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Product', new_product_path %>

参考資料

whereにSQLの文字列を渡したくない!

4
2
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
4
2