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...
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With