LoginSignup
31
25

More than 5 years have passed since last update.

ActiveRecord の scope で nil などを返した時の挙動

Posted at

ActiveRecord の scope で、引数の値が有効の場合にのみ、その値で条件を指定する以下のようなスコープを考えます

class Hoge < ActiveRecord::Base

  # 引数 name に値があれば、その値と name が同一のものでフィルタする
  scope :fuga, -> name do
    if name.present?
      where(name: name)
    else
      all # Rails3 の場合は all でなく scoped
    end
  end
end

実は scope の結果として nilfalse を返した時は all (Rails3 なら scoped) がそのまま適用されるようになっています。
ゆえに、上記コードのように明示的に all を返す必要はありません。
以下のように else は省略できます。

class Hoge < ActiveRecord::Base
  scope :fuga, -> name do
    if name.present?
      where(name: name)
    end
  end
end

なお、好みの問題ですがここまで短ければ自分の場合は1行で書く派。

class Hoge < ActiveRecord::Base
  scope :fuga, -> name { where(name: name) if name.present? }
end
31
25
2

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
31
25