如何将以下代码转换为适用于sqlite和mysql的代码?注意,internal是可以为空的。
scope :external, where("internal is not true")(在Rails 4中,可以简单地使用:)
scope :external, where.not(internal: true)发布于 2014-01-17 07:12:14
ActiveRecord足够聪明,可以做到这一点,只需做:
scope :external, where(internal: [false, nil])这将被转换成类似的SQL (可能带有表名和quetes ):
适用于internal IN ('f') OR internal IS NULL
internal IN (0) OR internal IS NULLPostgreSQL和SQLite MySQL的SQLite MySQL
如果需要更多的控制,你可以使用Arel:
scope :external,
where(arel_table[:internal].eq(false).or(arel_table[:internal].eq(nil)))这将是:
适用于internal = 'f' OR internal IS NULL
internal = 0 OR internal IS NULLPostgreSQL和SQLite MySQL的SQLite MySQL
请记住,如果需要检查SQL中的null值,请始终使用IS NULL或IS NOT NULL表达式。
表达式... <> NULL、... = NULL、... IN (NULL)对于所有内容都被评估为false。
因此,NULL <> NULL为false,NUL = NULL为false。
发布于 2012-03-14 12:31:08
尝试作用域:external,where('internal IN (?)',false,nil)
发布于 2011-10-12 11:05:04
试试scope :external, where(:internal => !true)
https://stackoverflow.com/questions/7734706
复制相似问题