Why Active Record relation is not returned in console?

爱⌒轻易说出口 提交于 2019-12-21 12:58:47

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/7646199/why-active-record-relation-is-not-returned-in-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!