Arelデビュー

Rails4.1

ArelはActiveRecordは中で使ってるライブラリ。詳しくはしらん。
ActiveRecord使ってるのになんで内部のライブラリを使わないといかんのかとか今まで必要になったことがなかったので使ってなかったけど今回は条件をorで繋げたくなったので仕方なく使った次第です。

class B < ActiveRecord::Base
  has_many :comments, as: :commentable
end
class A < ActiveRecord::Base
  has_many :comments, as: :commentable
end
class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

条件をorで繋げたくなったところ。

as = A.where(user: User.where(id: 1234))
bs = B.where(user: User.where(id: 1234))
Comment.where(commentable: (as + bs))

みたいにcommentableなレコードで検索したくなった。
このままだとin演算子が使われてレコードが万単位になってるとDBがお亡くなりになる(なった)のと大きな配列ができたりSQLが無駄に発行されウンコくさくなってしまう。
のでArelからorで条件を繋げたらで10万レコードでも動くコードになった。

as = Comment.where(commentable: A.where(user: User.where(id: 1234))).where_values.reduce(:and)
bs = Comment.where(commentable: B.where(user: User.where(id: 1234))).where_values.reduce(:and)
Comment.where(as.or(bs))
# http://stackoverflow.com/questions/7976358/activerecord-arel-or-condition

ActiveRecordの思想はよくわからないけどArelに触れない生活をしたいのでまじ頼むと思った。