Rails4 where句をnotで否定する
私は今まで、点数がある点数以外のときというスコープを下記のように書いていました。
scope :score_is_not, ->(score) {where("score != ?", score)}
いまさらですが、Rails4では、where句をnotで否定できるようです。
scope :score_is_not, ->(score) {where.not(score: score)}
もちろん、通常のActiveRecordでもnotは使えます。
Test.where.not(score: 0) # Test.where("score != 0")
また、INでもnotは使えるようです。
Test.where.not(score: [0, 100]) # Test.where("score NOT IN (0, 100)")
参考:
#400 What's New in Rails 4 - RailsCasts
Ruby on Rails で NOT IN な SQL をかく。 - そんなこと覚えてない