Rails 4 Relation#all deprecation

后端 未结 3 517
情深已故
情深已故 2021-01-17 12:25

In my app I created a recent posts feature.

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

This variable makes

相关标签:
3条回答
  • 2021-01-17 13:18

    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.

    0 讨论(0)
  • 2021-01-17 13:23

    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.

    0 讨论(0)
  • 2021-01-17 13:25

    Nested way

    Post.order('created_at DESC').limit(5).to_a
    
    0 讨论(0)
提交回复
热议问题