解决方法
当下?
present?
基本上不是零,不是空的?
class Object def present? !blank? end def blank? respond_to?(:empty?) ? !!empty? : !self end end
ActiveRecord条件
# Both lines lead to the same result: User.where.not(name: [nil,""]) User.where.not(name: nil).where.not(name: "")
因为没有原始的sql代码,所以不必担心如果它们与每个数据库适配器一起使用.实际上,这对MysqL和postgres都有效.
to_sql
如果您附加了.to_sql,例如在rails控制台中,您可以看到它们如何转换为SQL查询.
# rails console User.where.not(name: [nil,""]).to_sql # => "SELECT \"users\".* FROM \"users\" WHERE (NOT ((\"users\".\"name\" = '' OR \"users\".\"name\" IS NULL)))" User.where.not(name: nil).where.not(name: "").to_sql # => "SELECT \"users\".* FROM \"users\" WHERE (\"users\".\"name\" IS NOT NULL) AND (\"users\".\"name\" != '')"
进一步阅读
> [1] Rails 4 guide “ActiveRecord Query Interface”
> [2] Definition of present?
on github