ブログ

読んで思い出す。忘れるために書く

Q. 値があったときのみ検索したい (ActiveRecord)

A. scopeifall を使う

(自回答の転記)

teratail.com

class Board < ActiveRecord::Base
  scope :mypage_search, ->(user_id, search_params = {}) do
    where(user_id: user_id)
      .find_by_board_title(search_params[:title])
      .find_by_update_date(search_params[:updated_at])
  end

  scope :find_by_update_date, ->(updated_at) do
    return all if updated_at.nil?

    case updated_at
    when 3, 7
      where('updated_at > ?', updated_at.day.ago)
    else
      all
    end
  end

  scope :find_by_board_title, ->(title) do
    return all if title.nil?

    where('title LIKE ?', "%#{title}%")
  end
end
Board.mypage_search(1, title: 'foo', updated_at: 7)
#  Board Load (2.6ms)  SELECT "boards".* FROM "boards" WHERE "boards"."user_id" = 1 AND (title LIKE '%foo%') AND (updated_at > '2018-12-22 05:21:26.771
136')
# => #<Board::ActiveRecord_Relation:0x2b276b437778>