Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ActiveRecord and ActiveRecord::Relation objects

I have searched but not able to find the brief explanation for the difference between ActiveRecord and ActiveRecord::relation object.

I have understand that ActiveRecord is the single object find by something like

User.find(1)

And ActiveRecord::Relation is the array like object Find by something like

User.where(id: 1)

I am looking for the difference between them in terms of query execution or deep explanation about them, so it will clear the whole concept behind it.

Thanks in advance!

like image 307
power Avatar asked Jul 12 '16 09:07

power


2 Answers

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). Once you run that query by calling to_a, each, first etc. on that Relation a single instance or an array of ActiveRecord::Base instances will be returned.

like image 120
spickermann Avatar answered Oct 19 '22 13:10

spickermann


Rails uses activerecord as standard ORM but the same applies for activerecord on its own.

In short: all queries that yield multiple records like scopes, all, where, and joins return an ActiveRecord::Relation object. You can chain these together, and it is only when you use a method like to_sql, first, each, any, to_a, take, last etc that the query is executed and returns an array of ActiveRecord::Base instead


  • All this is explained on the following site

    • Especially the section on scopes, query methods and the examples for pluck show all the details on the main differences
  • See also the rails API for reference

like image 3
peter Avatar answered Oct 19 '22 12:10

peter