squeelというgemがかなり便利。
Arelで書けよって話なのですが、Arelで書くとコードが読みづらい・・・。
squeelで書くと大分SQLライクな感じになり、非常に読みやすくなります。
ここではクエリを組み立てる時にArelで書くようなところを、squeelではどう書くか書いていきます。
where
User.where { created_at >= 3.days.ago }
?とか必要なく書きやすい
or
User.where { (name == 'hoge') | (name == 'fuga') }
||ではなくsqueelで条件を繋げる場合は|で繋げます。
ちなみにandの場合は&で繋げます。
like
User.where { name.like '%hoge%' }
User.where { name =~ '%hoge%' }
likeまたは=~となります。
left join
User.joins { Group.outer }
非常に見やすい!
Predicates
| SQL | Predication | Operator | Alias |
|---|---|---|---|
| = | eq | == | |
| != | not_eq | != (1.9 only), ^ (1.8) | |
| LIKE | matches | =~ | like |
| NOT LIKE | does_not_match | !~ (1.9 only) | not_like |
| < | lt | < | |
| <= | lteq | <= | lte |
| > | gt | > | |
| >= | gteq | >= | gte |
| IN | in | >> | |
| NOT IN | not_in | << |
公式にこう書かれていますので、例えば前述のor検索などは、
User.where { (name.eq 'hoge') | (name.eq 'fuga') }
このように書くこともできます。
上記を組み合わせ、複雑な検索条件も、
User.joins { groups.outer }.where { (groups.name.not_eq 'hoge') }
User.where { (id >> [1, 2, 3]) & (name.matches_any ['%hoge%', '%fuga%']) }
と組み立てることが可能です。
Arelで複雑なコードを書いてる人は導入を検討してみてはどうでしょうか。
参考ページ:
https://github.com/activerecord-hackery/squeel
http://labs.timedia.co.jp/2013/11/activerecord4sql-squeel.html