LoginSignup
0
0

Rails Ransack 複数カラムを使用した絞り込み検索の実装

Posted at

検索機能を作っていると、単一のカラムだけではなく複数カラムを使った検索が必要になることがありますよね。
例えば、商品価格と送料を合計した値で絞り込みたいなど。
この記事では、RailsでRansackを使って複数カラムの合計値で絞り込み検索を実装する方法を紹介します。

実装の概要

モデルにransackerを定義する

まず、Productモデルにカスタムransackerを定義します。ここでは、item_priceとshipping_priceを合計したprice_totalという仮想的なカラムを作成します。

class Product < ApplicationRecord
  ransacker :price_total do
    Arel.sql('(item_price + shipping_price)')
  end
end

コントローラでの検索処理

次に、コントローラでRansackを使用して検索を実行します。以下はProductsControllerの例です。

class ProductsController < ApplicationController
  def index
    @q = Product.ransack(params[:q])
    @products = @q.result
  end
end

ビューでの検索フォーム

最後に、ビューで検索フォームを作成します。以下は、price_totalが指定の値以上の商品をフィルタリングするための検索フォームの例です。

<%= search_form_for @q do |f| %>
  <%= f.label :price_total_gteq, "合計価格が指定以上" %>
  <%= f.number_field :price_total_gteq %>
  <%= f.submit "検索" %>
<% end %>

まとめ

これで、商品価格と送料の合計が指定された値以上の商品をRansackでフィルタリングできるようになりました。
Ransackを使うことで、カスタムransackerを定義し、複数カラムを使った複雑な検索条件も簡単に実装できます。

0
0
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
0
0