Why Active Record relation is not returned in console?
Asked Answered
L

2

6

I have finally started upgrading my Rails apps from 2.3.8 to 3.1.0. I was watching RailsCasts (http://railscasts.com/episodes/202-active-record-queries-in-rails-3) about Active Record queries.

When I open up the console (rails c) and do query similar to this:

articles = Article.order("name")

Instead of returning Active Record relations, I see the query executed. What am I doing wrong here?

Rails version: 3.1.0

RVM on 1.9.2

Thank you for your help!


EDIT: I have added a screenshot from the example. enter image description here

Lillie answered 4/10, 2011 at 10:2 Comment(0)
F
8

You're doing everything right. You see query executed because console invokes inspect method on output. Try articles = Article.order("name").class

Fascist answered 4/10, 2011 at 10:6 Comment(2)
Thanks, that seems to be the issue. I have added a screenshot from the example. Do you have any idea why the inspect method is not invoked in the example video?Lillie
Man, did I struggle with this the first time I tried playing with Arel.Peisch
G
9

The ActiveRecord Relation class is configured to perform the query when a query method like .all, .last, .first, ... is invoked. The list of method also includes .inspect, the same method called by the console to display the representation of the return value.

For this reason it seems to you that the object is never a relation, because you always see the result of the query.

But if you inspect the object class, you'll notice it's a relation

Article.order("name").class
# => ActiveRecord::Relation
Gormand answered 4/10, 2011 at 10:22 Comment(1)
Thanks for the answer! I chose Bohdan's answer because he posted it a bit earlier. +Lillie
F
8

You're doing everything right. You see query executed because console invokes inspect method on output. Try articles = Article.order("name").class

Fascist answered 4/10, 2011 at 10:6 Comment(2)
Thanks, that seems to be the issue. I have added a screenshot from the example. Do you have any idea why the inspect method is not invoked in the example video?Lillie
Man, did I struggle with this the first time I tried playing with Arel.Peisch

© 2022 - 2024 — McMap. All rights reserved.