Sorry if this has been still answered, I haven’t found nothing on it. I would love to know why ActiveRecord::Base#last doesn’t return an ActiveRecord::Relation just like all or where since an ActiveRecord::Relation can act more or less like an array (as specified here)?
Thanks, have a nice day.
Because you won’t need to run a query on one element?
I think the question is more about Model.last(5) or Model.first(5)
These return arrays when they could return a relation.
“first” and “last” have always returned an instance of the model. These are meant to be the final method that you call on a relation, to get the result. If you call “last(5)” it will return an array, and that’s the correct behaviour since that’s the result of the query. If you need the relation so you can add other criteria on top of it, you can still use “limit(5).order(arel_table[:id].desc)”
Gotcha. In this case, since calls to Model.last(n) is inherently inefficient (loading everything and placing a limit), it’s good to keep it till the end of the chain.
“last(5)” is, with regard to efficiency, equivalent to “limit(5).to_a”.