【发布时间】:2020-01-09 05:39:19
【问题描述】:
我的应用程序即将陷入困境。有人可以帮我优化这个控制器代码以更快地运行吗?或者指出我正确的方向。 我正在尝试显示由 active 定义的客户列表为 true,而 active 为 false 的潜在客户列表。存档的客户是真实的。 谢谢你。
if current_user.manager?
get_customers = Customer.where(:archived => false)
@cc = get_customers.where(:active => true)
@current_customers = @cc.where(:user_id => current_user.id)
@count_current = @current_customers.count
@pc = get_customers.where(:active => false)
@potential_customers = @pc.where(:user_id => current_user.id)
@count_potential = @potential_customers.count
end
这对提高速度有何影响?
型号
scope :not_archived, -> { where(:archived => false) }
scope :current_customers, -> { where(:active => true).not_archived }
scope :potential_customers, -> { where(:active => false).not_archived }
scope :archived_customers, -> { where(:archived => true) }
控制器
@current_customers = Customer.current_customers.includes(:contacts,:contracts)
查看
link_to "Current Clients #{@count_current.size}"
【问题讨论】:
-
这取决于您到底想要什么,但现在他们的代码存在严重问题,您正在检索完整的客户列表,这意味着它将占用太多内存,而不是您查询它。第一个解决方案是使用分页,它会给你总数,并只返回有限的 10 条记录,但你将无法使用 :active => true!因此,请尝试考虑您必须在视图中显示的确切内容,并修改记录以仅获取包含、连接和其他选择特定查询的内容。另一种技术可以是检查数据库端创建了什么查询并使用解释查询。
标签: ruby-on-rails activerecord ruby-on-rails-5