この問題に何度か遭遇しました。クエリにスコープを適用したいのですが、スコープに渡されたパラメーターが null でない場合に限ります。そう
tags = Tag.where(name: params[:name]) if params[:name]
ただし、これには 2 つの問題があります。1 つは、Rails がクエリをすぐに評価するため、さらに条件を適用したい場合は、
tags.where(location: params[:place]) if params[:place]
DBに再度クエリを実行します。2 番目の問題は、見栄えがよくないことです。これは、クラス メソッドで回避しようとしました。
class Tag < ActiveRecord::Base
def self.name_like this_name
if !this_name.blank?
where("name ILIKE '%#{this_name}%'")
else
#what do I put here? `all` does not work
end
end
end
all
ただし、クエリを評価するため、単純にそこに入れることはできません。何かご意見は?