2013-02-23 39 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

相關問題