2013-02-23 40 views
0

在我们的Rails 3.2的应用程序,我们需要检索所有客户记录了客户表,并将其分配给一个变量customers并做查询(如。凡(:主动=>真)可变customers下旬有2问题在这里:。如何高效地检索rails 3.2中的所有记录并将它们分配给可查询的对象?

  1. 有什么更好的方式来获取所有记录

    Customer.all作品然而,根据轨道的文件,它可能有性能问题时,客户表变大,我们试图Customer.find_each它有错误"no block given (yield)"

  2. 如何使变量customers query_able?

    当对可变customers查询(如customers.where(:active => true)),有一个错误:undefined method其中”为#. It seems that the客户is an array object and can't take其中. How can we retrieve客户`以这样的方式也可以是可查询?

感谢您的帮助。

回答

2

在Rails 立即使数据库调用,负载记录并返回数组。取而代之的是使用“惰性”scoped方法,该方法返回可链式对象ActiveRecord::Relation。例如: -

customers = Customer.scoped 
... 
customers = customers.where(:active => true) 
customers = customers.where(...) 
etc... 

而此刻,当你将需要加载的记录,并在它们之间迭代,你可以拨打find_each

customers.find_each do |customer| 
    ... 
end 
+0

在我们的Rails 3.2.12范围的作品。谢谢。顺便说一下,它在轨道4中被弃用了吗? – user938363 2013-02-23 21:03:55

+0

是的,它已被弃用。在Rails 4中,'all'方法相当于'scoped' – 2013-02-24 09:41:08

相关问题