sscirrus
sscirrus

Reputation: 56719

Find all records that have a non-nil field?

I am trying to define two variables as follows:

  1. @orders = Customer.find_all_by_order_date(nil)
  2. @nonorders = Customer.find_all_by_order_date(!nil)

The first works properly but the second doesn't. How can I find those customers whose order_date fields are not nil?


@nonorders = @customer.orders.find(:all, :conditions => "@customer.orders.order_date IS NOT NULL")

is giving me the following error:

undefined method 'extract_options_from_args!' for ActiveRecord::Base:Class

I've tried changing the conditions, such as @orders.order_date, @customer.order.order_date, etc. What's causing this error? Thank you!

Upvotes: 10

Views: 12272

Answers (3)

copremesis
copremesis

Reputation: 776

> Rails 3.x

@nonorders = Customers.where("date IS NOT NULL")


Unless you are doing some non rails conventional stuff,
there should be no need to specify the table name within
the SQL payload of the the where method

Upvotes: 0

Tom Close
Tom Close

Reputation: 620

The string you pass as :conditions needs to be an sql fragment.

In the example given "customers.date" refers to the date field of the customers table. I think the "customers" bit is not strictly necessary, as the table name is clear from the context.

In your example the following should work:

@nonorders = @customer.orders.find(:all, :conditions => "order_date IS NOT NULL")

Upvotes: 1

Yannis
Yannis

Reputation: 5426

Rails3:

@nonorders = Customers.where("customers.date IS NOT NULL")

Rails2:

@nonorders = Customers.find(:all, :conditions => "customers.date IS NOT NULL")

Upvotes: 22

Related Questions