开发者

is there a nicer/rails-like way for find all where something IS NOT NULL query?

开发者 https://www.devze.com 2023-01-16 03:35 出处:网络
is there a nicer/rails-like way for this IS NOT NULL query? MyModel.find(:all, :conditions=&开发者_Go百科gt;\"some_reference_id IS NOT NULL\")The more Rails-like way would be with scopes, since they

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

MyModel.find(:all, :conditions=&开发者_Go百科gt;"some_reference_id IS NOT NULL")


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消