Rails 4 Relation#all deprecation

↘锁芯ラ 提交于 2019-12-19 14:58:08

问题


In my app I created a recent posts feature.

 @recentposts = Post.all(:order => 'created_at DESC', :limit => 5)

This variable makes some trouble. When I run tests I have the following error:

DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, 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.where(published: true).to_a). (called from show at /home/mateusz/rails4/Bloggers/app/controllers/users_controller.rb:18)

I was seraching solution on Google but I don't find it...


回答1:


Just write:

@recentposts = Post.order('created_at DESC').limit(5)

The to_a is not explicitly necessary, as the data is lazy loaded when needed.




回答2:


A call to Post.all will return an ActiveRecord::Relation, which will be loaded lazily by default. Calling Post.all.load will return an eagerly-loaded ActiveRecord::Relation. Finally, calling Post.all.to_a will return all records in an array.

In your case you would do:

Post.order('created_at DESC').limit(5).to_a

which would return an array of the first 5 Posts, sorted by created_at in descending order.




回答3:


Nested way

Post.order('created_at DESC').limit(5).to_a


来源:https://stackoverflow.com/questions/18203712/rails-4-relationall-deprecation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!