dmitryck
dmitryck

Reputation: 61

Independent ActiveRecord query inside ActiveRecord::Relation context


There is some ruby on rails code

class User < ActiveRecord::Base
  def self.all_users_count
    User.all
  end
end

User.all_users_count
returns, for example, 100

User.limit(5).all_users_count
Now it return 5 because of ActiveRecord::Relation context, in despite of i wroute name of class User.all instead simple all
(.to_sql show that query always contains limit or where id or other things in other cases)

So, how can i make context-independent AR queries inside model methods? like User.all and others?

Thank you!

Ps. Or maybe my code has an error or something like this, and in fact User.all inside any methods and context always must returns correct rows count of this model table

Upvotes: 2

Views: 270

Answers (1)

Greg
Greg

Reputation: 6659

This is very weird and unexpected (unfortunately I can't confirm that, because my computer crashed, and have no rails projects at hand).

I would expect

User.all 

to create a new scope (or as you call it - context)

Try working around this with

User.unscoped.all

Edit:

I tried it out on my project and on clean rails repo, and the results are consistent.

And after thinking a bit - this is maybe not even an issue - I think your approach could be faulty.

In what scenario would you chain User.limit(2).all_users_count ?? I can't think of any. Because either you need all users count, and you call User.all_usert_count (or just User.count)

... or you need something else and you call User.limit(2).where(...) - there's no point in calling all_users_count in that chain, is it?

And, when you think of it, it makes sense. Imagine you had some different method like count_retired, what would you expect from such call:

User.limit(2).count_retired ?

The number of retired users not bigger than 2, or the number of all retired users in the system? I would expect the former.

So I think one of two possibilities here:

  • either you implemented it wrong and should do it in a different way (as described above in the edit section)
  • or you have some more complex issue, but you boiled your examples down to a point where they don't make much sense anymore (please follow up with another question if you please, and please, ping me in the comment with a link if you do, because it sounds interesting)

Upvotes: 1

Related Questions