user938363
user938363

Reputation: 10350

How to efficiently retrieve all record in rails 3.2 and assign them to a query-able object?

In our rails 3.2 app, we need to retrieve all customer records out of customer table and assign them to a variable customers and do query (such as .where(:active => true) on variable customers late on. There are 2 questions here:

  1. what's the better way to retrieve all records?

    Customer.all works. However according to rails document, it may have performance issue when Customer table gets large. We tried Customer.find_each and it has error "no block given (yield)".

  2. How to make the variable customers query_able?

    When performing query on variable customers (like customers.where(:active => true)), there is an error: undefined methodwhere' for #. It seems that thecustomersis an array object and can't takewhere. How can we retrievecustomers` in such a way it can be query-able?

Thanks for help.

Upvotes: 0

Views: 212

Answers (1)

Babur Ussenakunov
Babur Ussenakunov

Reputation: 1995

In Rails < 4 .all makes database call immediately, loads records and returns array. Instead use "lazy" scoped method which returns chainable ActiveRecord::Relation object. E.g.:

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

And at the moment when you will need to load records and iterate over them you can call find_each:

customers.find_each do |customer|
  ...
end

Upvotes: 2

Related Questions