Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Relation#all deprecation

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...

like image 806
Mateusz Urbański Avatar asked Aug 13 '13 08:08

Mateusz Urbański


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is ActiveRecord relation?

An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

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.

like image 84
nathanvda Avatar answered Sep 20 '22 11:09

nathanvda