On Jul 18, 2011, at 5:16 PM, Glenn Little wrote:
> Poking my nose into Rails 3, I notice that the class of the returned
> values of these two calls is not the same:
>
> Model.all ==> returns Array
> Model.where(['1 = 1']) ==> returns ActiveRecord::Relation
>
> Is there a reason this is this way? What I would think is a common use case:
>
> Model.all.order("somefield DESC")
>
> fails with NoMethodError: undefined method 'order' for
> #<Array:xxxxxxx> (where it works fine with the "where 1=1" instead)
>
> The I guess older style "Model.find(:all)" also returns an array so it
> too is un-scope-able in the above way.
>
> I *can* do Model.order("somefield DESC"), but that just seems
> inconsistent (albeit handy).
>
> So what is conceptually different about Model.all.order() compared to
> Model.order() and Model.where(['1 = 1']).order()?
ActiveRecord in Rails 3 tries to be lazy. So you can queue up all kinds of
modifiers to your query separately, and then execute them all together when
you’re ready. .all is one way to trigger the actual query happening, and thus
the conversion of a lazy query object into a result set.
--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby