LoginSignup
3
2

More than 1 year has passed since last update.

Rails 検索機能 数値

Last updated at Posted at 2022-10-03

Railsで数値を検索する機能を作る機会があったので
メモとして残しておきます!

目次

  1. 今回作るもの
  2. Viewの作成
  3. Controllerの編集
  4. 入力フィールドをSelectで実装

イメージが沸くように見た目(View)から作っていきます🙌

今回作るもの

image.png
上記の画像のように、投稿内容や投稿タイトルに関する文字列検索機能とは
また別に金額に関して、最大値と最小値を入力して検索をかけます!
select_tagでわかりやすく範囲にしても良さそうですね!

Viewの作成

検索機能に該当する部分はこんな感じです!
パラメータ(実質クエリ、URLに載るもの)で2つの値を渡せるようにしておきます!
検索するボタンを押すと、
URLは/posts?min_search=0&max_search=&commit=価格検索するのようになります!

index.html.erb
<div class="search-box">
    <div class="search-form">
        <%= form_tag({controller:"posts",action:"index"}, method: :get) do %>
            <i class="fas fa-search"></i>
            <%= number_field_tag :min_search, "", placeholder: "最小価格" %>
            <%= number_field_tag :max_search, "", placeholder: "最大価格" %>
            <%= submit_tag "価格検索する", id: "submit" %>
        <% end %>
    </div>
</div>

form_tagに関する内容はRailsドキュメントで確認しておくと良いでしょう!

Controllerの編集

posts_controller.rb
    def index
        search = params[:search]
        min_search = params[:min_search]
        max_search = params[:max_search]
        if search != nil && search != ''
            #部分検索かつ複数検索
            @posts = Post.joins(:user).where("body LIKE ? OR name LIKE ?", "%#{search}%", "%#{search}%")
        elsif max_search != '' && max_search != nil && min_search != '' && min_search != nil
            @posts = Post.where("price >= #{min_search} and price <= #{max_search}")
        elsif max_search != '' && max_search != nil
            @posts = Post.where("price <= #{max_search}")
        elsif min_search != '' && min_search != nil
            @posts = Post.where("price >= #{min_search}")
        else
            @posts = Post.all
        end
    end

今回は、以下のように書いています。
調べたいカラムを持つモデル名.where("カラム名 >= #{params[:設定したパラメータ名]}")
andorで複数の条件を設定できます!

入力フィールドをSelectで実装

Viewを以下のように変更します

index.html.erb
<div class="search-box">
    <div class="search-form">
        <%= form_tag({controller:"posts",action:"index"}, method: :get) do %>
            <i class="fas fa-search"></i>
            <%= select_tag :min_search, options_from_collection_for_select(@price, "id","price") %>
            <%= select_tag :max_search, options_from_collection_for_select(@price, "id","price") %>
            <%= submit_tag "価格検索する", id: "submit" %>
        <% end %>
    </div>
</div>

options_from_collection_for_selectでは、
特定のモデルから取得した値のidカラムを指定することで、
そのカラムに関するデータを利用して、選択肢を生成してくれます!

また、Controllerは以下のように変更しました!

def index
    search() # 先ほどの検索部分を別のメソッドにして省略
    @price = Post.select("price")
end

特定のカラムだけ取得するには、モデル名.selectで可能です!

以上で終わりになります!
Whereを工夫するだけで、いろんな検索機能を作れるので、
もっと遊びたい方は、いろんなデータを検索できるように作ってみるなど
してみましょう✨

参考文献

3
2
1

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