我想对表执行 SQL 查询。我遇到了无法继续的问题。
如何使用 Active Record 查询列不相等的表 归零?当前的查询如下所示,但它不起作用,因为它给了我一个空值。
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
关于mysql - Rails - Active Record 中不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587559/