如何避免损坏的 Arel 查询归档 RAM
当控制器操作在开发中发生故障时,我们通常会得到包含一些有用信息的回溯。当生产中发生同样的情况时,我们会通过电子邮件获取并向访问者显示 404。无论哪种方式,我们都有某种错误处理来检查实例及其变量。
现在,当检查不完整的 Arel 查询时,它会加载很多对象。下面是一个示例:
def index
@users = User.order("name asc")
if params[:query]
@users = @users.where("username like ?", "%{params[:query]}%")
else
@users = @users.limit(20)
end
end
当条件内部的某些内容发生故障时,@users 变量会陷入 User.order("name asc")
状态,并且在检查时,它会加载数据库中的所有用户<强>填满内存。
有办法避免这种情况发生吗?
When a controller action blows up in development, we usually get a backtrace with some useful info. When the same happens in production, we get it via email and display a 404 to the visitor. Either way we have some kind of error handling that inspects the instance and its variables.
Now when an incomplete Arel query gets inspected, it loads up a LOT of objects. Here is an example:
def index
@users = User.order("name asc")
if params[:query]
@users = @users.where("username like ?", "%{params[:query]}%")
else
@users = @users.limit(20)
end
end
When something inside the conditional blows up, the @users variable gets stuck with User.order("name asc")
and when inspected, it loads up all the users from the database filling up the RAM.
Is there a way to avoid this from happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用合理的
LIMIT
覆盖预初始化您的@users
,然后将其取消怎么样?What about preinitializing your
@users
with a saneLIMIT
override, then cancelling it out later?最后,我劫持了 ActiveRecord::Relation 的 #inspect 方法,如下所示: https://github .com/rails/rails/pull/2623
In the end, I hijacked the #inspect method of ActiveRecord::Relation like so: https://github.com/rails/rails/pull/2623