本文介绍了限制无法在Rails3中正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的操作控制器索引方法中包含以下代码:

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

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

不幸的是,限制调用不起作用,并且@practices返回> 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.

更新

SQL日志:

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 %>

有什么建议吗?

TIA

推荐答案

似乎您正在正确返回有限的集合并将其存储在 @practices 实例变量中.

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

但是,您正在使用 @ activity.practices 渲染您的部分内容,这将触发整个无限实践集合的延迟加载,因为该集合尚未加载到 @上活动对象.

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.

答案

<%= render @practices%> 应该可以.

奖励回合

最后,如果您想要更多面向对象"的东西,则可以将有限"查询放入名为"recent_practices"的范围中,这样您就可以调用:

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%>

上面的示例将在局部变量中使用一个名为"recent_practices"的局部变量,而不是实例变量.

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

有关此处的ActiveRecord范围.

这篇关于限制无法在Rails3中正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 18:42