Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: alternative for ActiveRecord 'all' as it is now deprecated

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%")
like image 926
Rots Avatar asked Oct 28 '25 08:10

Rots


1 Answers

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.

like image 137
Colto Avatar answered Oct 29 '25 23:10

Colto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!