2015-03-13 48 views
1

我有这样的查询: query = Link.select('url, max(created_at) as created_at, count(*) as url_count').group(:url).order('url_count desc, created_at asc')为什么组计算字段不显示在查询结果中?

query.results.first样品结果:

2.2.0 :002 > query.first 
=> #<Link id: nil, url: "http://1", created_at: "2015-03-10 16:43:54"> 

为什么这里没有url_count,尽管我知道它是。

2.2.0 :003 > query.first.url_count 
=> 17 

回答

5

计数一直存在,但模型to_s方法不知道它。

当您的控制台记录query.first的结果时使用的to_s方法在activerecord的某处定义,它使用为数据库中的模型定义的属性。由于您的属性仅为Link的此特定实例定义,不适用于型号Link

我发现这很有趣。以下描述了如何构建控制台中显示的消息。它开始了创业板active_attr下面显示的这3种方法:

def inspect 
    attribute_descriptions = attributes.sort.map { |key, value| "#{key}: #{value.inspect}" }.join(", ") 
    separator = " " unless attribute_descriptions.empty? 
    "#<#{self.class.name}#{separator}#{attribute_descriptions}>" 
end 

# ... 

def attributes 
    attributes_map { |name| send name } 
end 

# ... 

def attributes_map 
    Hash[ self.class.attribute_names.map { |name| [name, yield(name)] } ] 
end 

方法attributes_names在宝石activerecord

def attribute_names 
    @attribute_names ||= if !abstract_class? && table_exists? 
     column_names 
    else 
     [] 
    end 
end 

# ... 

def column_names 
    @column_names ||= @connection.columns(@table_name).collect { |c| c.name } 
end 

定义,这就是为什么你算不出来。

如果你真的希望它显示在你的控制台,你可以覆盖inspect方法并将其添加到那里。