4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails5版 OR クエリ構築するマン

Last updated at Posted at 2017-11-28

注意

6.2版はこちら

概要

Rails4 時代に使っていた where.or 記述を Rails5 でも活用する

理由

Rails5から #or が実装されたため静的な条件なら where.or が無くても困らない

User.where.or(User.fuga, User.hoge) #=> Rails4#where.or
User.fuga.or(User.hoge)             #=> Rails5#or

ただし動的な条件の場合、Rails5#or だけでは可読性が落ち、毎回記述したくない

User.where.or(*or_conditions)  #=> Rails4#where.or

first_condition = or_conditions.shift #=> Rails5#or
or_conditions.inject(first_scope) do |merged_scope, scope|
  merged_scope.or(scope)
end

実装

余り複雑にするとRailsのVerUpでまた困るので引数のハッシュ対応は削除しました

ActiveRecord::QueryMethods::WhereChain.include(Module.new do
  def or(first_scope, *scopes)
    or_scope = scopes.inject(first_scope) do |merged_scope, scope|
      merged_scope.or(scope)
    end

    @scope.merge!(or_scope)
    @scope
  end
end)
or_conditions = [User.where(id: 2), User.where(id: 3)]
User.where(id: 1).where.or(*or_conditions).where(id: 4).to_sql
=> "SELECT `users`.* FROM `users` 
    WHERE `users`.`id` = 1 AND (`users`.`id` = 2 OR `users`.`id` = 3) AND `users`.`id` = 4"

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?