Reputation: 10350
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:
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)"
.
How to make the variable customers
query_able?
When performing query on variable customers
(like customers.where(:active => true)
), there is an error: undefined method
where' for #. It seems that the
customersis an array object and can't take
where. How can we retrieve
customers` in such a way it can be query-able?
Thanks for help.
Upvotes: 0
Views: 212
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