2

Recently I've been using ModelName.where(nil) in certain situations when I might use ModelName.all.

The difference between the two is that the former returns an ActiveRecord Relation, whereas the latter returns an array. I can chain queries off the former, but not the latter. I'm not pleased that I lose the self-documenting nature of ModelName.all though.

Is there some method like ModelName.all that returns an AR Relation and maintains self-documentation?

Eric Hu
  • 18,048
  • 9
  • 51
  • 67
  • 1
    the where(nil) is a really nice workaround for always returning a relation. Maybe in the cases where you aren't sure whether or not you will return a relation or the class - you could add a class method on ActiveRecord::Base, i.e. def self.prepare; where(nil); end. – Omar Qureshi Feb 25 '12 at 19:29

3 Answers3

1

ModelName.scoped will give you an AR relation with the default scope, ModelName.unscoped will give the the AR relation without the default scope.

Derek Hall
  • 201
  • 2
  • 3
  • 1
    I didn't know about these. Definitely useful to know. I'm not sure if I'll use this one since [this response](http://stackoverflow.com/a/4166950/640517) mentions that `unscoped` can be dangerous to use on associations. I.e. in my current project: `User.first.posts # => []` but `User.first.posts.unscoped # => all posts, by ANY user`. – Eric Hu Feb 27 '12 at 04:06
1

In that case you can use ModelName as you can't use all bcz it returns array.

E.g.

a = ModelName
a = a.active # here active is scope
a = a.where(:deleted => false)
a = a.all
Sandip Ransing
  • 7,583
  • 4
  • 37
  • 48
  • I don't believe I can enumerate over `ModelName` alone: `ModelName.each {|obj| ...} # no each method defined for ModelName`. Compare with `ModelName.where(nil).each {...}` and `ModelName.all.each {...}` Both work in case I don't need to scope deeper. – Eric Hu Feb 27 '12 at 03:44
-1

Well I normally use

Model.find(:all, :conditions=>whatever, :order=>whatever,:limit=>whatever)

In your case maybe Model.find(:all) will do the trick for you

phoenixwizard
  • 5,079
  • 7
  • 27
  • 38
  • `Model.find(:all)` returns an array. You cannot chain onto it. Try `Model.find(:all).classMethod` for `classMethod` defined on `Model`. – Eric Hu Feb 27 '12 at 03:47
  • I always remembered getting an array of Active record objects and I thought that was needed. My misunderstanding of the question. Thanks for telling me about it :) – phoenixwizard Feb 27 '12 at 12:02