views:

49

answers:

2

is there a nicer/rails-like way for this IS NOT NULL query?

MyModel.find(:all, :conditions=>"some_reference_id IS NOT NULL")

+1  A: 

Assuming MyModel belongs_to :some_reference, you could also use

  1. MyModel.all.find_all{ |e| e.some_reference } or
  2. MyModel.all.find_all{ |e| e.some_reference_id }

really depends on what you are trying to achieve. (2.) would be equivalent (in terms of result contents) to your IS NOT NULL query, (1.) will only return records whose some_reference_id is not null AND points to valid some_references record.

amba
Full table scan.
Mark Thomas
+5  A: 

The more Rails-like way would be with scopes, since they are now native to Rails 3. In Rails 2, you can use named_scope which is similar.

class MyModel < ActiveRecord::Base
  named_scope :referenced, :conditions => "some_reference_id IS NOT NULL"
end

#Then you can do this
MyModel.referenced

In Rails 3 it would be something like this.

class MyModel < ActiveRecord::Base
  scope :referenced, where "some_reference_id IS NOT NULL"
end
Mark Thomas
Named scopes are cleaner and more elegant way.. +1
sameera207