Reputation: 1280
@category = Category.where(:category_name => 'cricket')
@category.class
Here the class of @category is "ActiveRecord::Relation" But,
@category = Category.all(:conditions => { :category_name => 'cricket' })
@category.class
In this case the class of @category is "Array"
The result of both the queries are same, then also the class is different. WHY?
One more thing... In the first case, I can do @category.title or @category.body etc. But in second case, It is not possible. WHY?
Upvotes: 2
Views: 668
Reputation: 13925
In the first case you are actually using the default scope and attribute it with the where
part. It means, when you want to use the items of this Relation, it will run the SQL query on demand. Think about it like it is prepared, but not yet ran query, which will yield walues when needed, and you can further specify the parameters, for example you can append another where clause, or something to it. And of course it is smarter than a simple array, because of the implementetion is more complex behind this.
In the second case you immediately fetch all record from the database, so the result is an Array, containing the results. It is pretty dumb compared to the other one.
Upvotes: 2