Limit not working as expected in Rails3

2019-07-31 14:11发布

问题:

I have the following code in my practices controller index method:

@practices = @activity.practices.order('created_at DESC').limit(20)

Unfortunately, the limit call is not working, and @practices is returning >20 objects. I'm sure this is a simple thing to fix, but I'm not sure what I'm doing wrong. I seem to be using this method in the way prescribed in the docs..

I have tried placing the call to limit before the order call, with the same result.

UPDATE

SQL LOG:

Practice Load (1.6ms)  SELECT "practices".* FROM "practices" WHERE ("practices".activity_id = 9) ORDER BY practiced_on DESC, created_at DESC LIMIT 20

However, further down the log, I found this:

   Rendered practices/_practice.html.erb (216.9ms)
  Activity Load (0.6ms)  SELECT "activities".* FROM "activities" WHERE ("activities".user_id = 1)
  Practice Load (0.8ms)  SELECT "practices".* FROM "practices" WHERE ("practices".activity_id = 8) ORDER BY practiced_on DESC
  CACHE (0.0ms)  SELECT "practices".* FROM "practices" WHERE ("practices".activity_id = 9) ORDER BY practiced_on DESC

Which leads me to think that the partial is not accepting the correct collection. The partial is called thus:

<%= render @activity.practices %>

Any advice?

TIA

回答1:

It looks like you are returning your limited collection correctly and storing it in the @practices instance variable.

However, you are rendering your partial with @activity.practices, which will trigger a lazy load of the entire unlimited practices collection, because that collection has not yet been loaded on the @activity object.

The answer

<%= render @practices %> should work.

Bonus round

Finally, if you want something a little more 'object-oriented' you could put your 'limited' query into a scope called 'recent_practices' so you could call:

<%= render :partial => 'practices', :object => @activity.recent_practices %>

The above example would use a local variable called 'recent_practices' inside the partial, rather than an instance variable.

More about ActiveRecord scopes here.