以下查询应该可以正常工作但不起作用。
class Keyword
def self.popular_queries
t = Time.now
relation = Keyword.where(:created_at => (t.beginning_of_day..t.end_of_day))
relation = relation.group(:name)
relation = relation.select("name, COUNT(id) AS count_value")
relation.to_a
end
end
结果是没有计数值
[#<Keyword name: "a">, #<Keyword name: "b">,
#<Keyword name: "c">, #<Keyword name: "d">]
keywords表只有两列name
和id。
解决方案
def self.popular
t = Time.now
relation = Keyword.where(:created_at => (t.beginning_of_day..t.end_of_day))
relation = relation.group(:name)
relation = relation.select("name, created_at, count(*) as c1")
sql = relation.to_sql
self.connection.select_all(sql)
end
答案 0 :(得分:1)
问题是您的Keyword
模型不知道count_value
是什么,并且您基于SQL查询实例化了一堆Keyword
个实例。创建实例后,他们会在他们提交的数据中看到count_value
但他们会忽略它,因为它们没有count_value
属性。
如果您想运行任意SQL并获取简单数据,您应该使用select_rows
或类似的低级方法。