Frage

Is find_each an acceptable replacement for the ActiveRecord function all in version 4.0.0 of ActiveRecord?

For example, previously I had:

all_users = User.all

which produces a warning stating something along the lines of ActiveRelation:all is deprecated.

As a replacement I came up with:

User.find_each do |user|
  all_users += user
end

Is this acceptable, or should I be doing it another way?

I understand the reason behind using find_each is because of 'batching' which will allow the query to stop running if there is a very large dataset. Let's assume for this case that the dataset is small.

EDIT

It seems the deprecation error only comes up when you use conditons, eg:

User.all(:conditions => ["name like ?", "%bob%"]) 

produces:

DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a rel ation, you can call #load (e.g. Post.where(published: true).load). If you want to get an array of records from a relation, you can call #to_a (e.g. Post.wher e(published: true).to_a). (called from irb_binding at (irb):8)

The correct replacement for the above appears to be:

User.where("name like ?", "%bob%")
War es hilfreich?

Lösung

Model.all isn't deprecated in Rails 4, but it has changed. Instead of returning an array of all of the records, it returns an ActiveRecord Relation which is significantly faster.

Model.all is designed to deprecate Model.scoped which previously lazy loaded the records. Model.all can now be used for easier chaining of methods instead of scoped.

You can read all about it here in this article.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top