Albert Paul
Albert Paul

Reputation: 1208

Rails - Not equal in Active Record

I want to execute a sql query against a table. I'm experiancing a problem in which I cannot proceed.

How can I use Active Record to query a table where column is not equal to null? Current query is given below but it's not working as it gives me a null.

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

I want to get count of sweets whose id's are included in array_of_cookies and artificial_sweetner is not null.

Below code works just fine but I need it in Rails way or say I'll need objects to manipulate.

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

I'm using ruby 1.9 and Rails 3.2.

Upvotes: 1

Views: 1194

Answers (2)

Edward
Edward

Reputation: 1914

you can just put the where clause as string inside the where call:

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

Or in Rails 4 You can do something like this:

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

Upvotes: 2

messanjah
messanjah

Reputation: 9278

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

Upvotes: 0

Related Questions