rails3 group by sqlite3

时间:2011-04-14 17:39:38

标签: ruby-on-rails

以下查询应该可以正常工作但不起作用。

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

1 个答案:

答案 0 :(得分:1)

问题是您的Keyword模型不知道count_value是什么,并且您基于SQL查询实例化了一堆Keyword个实例。创建实例后,他们会在他们提交的数据中看到count_value但他们会忽略它,因为它们没有count_value属性。

如果您想运行任意SQL并获取简单数据,您应该使用select_rows或类似的低级方法。