Rails - 在 Active Record 中不相等

Rails - Not equal in Active Record

我想对 table 执行 sql 查询。我遇到了无法继续的问题。

如何使用 Active Record 查询列不相等的 table 为空?当前查询在下面给出,但它不起作用,因为它给了我一个空值。

no_sweets = CookieJar.where(cookie_id: array_of_cookies, artificial_sweetner: !nil).count

我想统计 ID 包含在 array_of_cookies 中且 artificial_sweetner 不为空的糖果数量。

下面的代码工作得很好,但我需要它 Rails 方式或者说我需要对象来操作。

no_sweets = CookieReportingDb.connection.execute("SELECT count(*) FROM cookie_db_new.cookie_jars where artificial_sweetner is not null and cookie_id IN (#{array_of_cookies.join(', ')})").first

我正在使用 ruby 1.9 和 Rails 3.2。

您可以将 where 子句作为字符串放在 where 调用中:

no_sweets = CookieJar.where("artificial_sweetner is not null").where(cookie_id: array_of_cookies).count

或者在 Rails 4 你可以这样做:

no_sweets = CookieJar.where.not(artificial_sweetner: nil).where(cookie_id: array_of_cookies).count

Rails 3

no_sweets = CookieJar.where(cookie_id: array_of_cookies).where("artificial_sweetner IS NOT NULL").count

Rails 4

no_sweets = CookieJar.where(cookie_id: array_of_cookies).where.not(artificial_sweetner: nil).count