开发者

rails3 group by issue with sqlite3

开发者 https://www.devze.com 2023-02-24 14:09 出处:网络
Following query should work but it is not working. class Keyword def self.popular_queries t = Time.now relation = Keyword.where(:created_at => (t.beginning_of_day..t.end_of_day))

Following query should work but it is not working.

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

result is following without count value

[#<Keyword name: "a">, #<Keyword name: "b">, 
#<Keyword name: "c">, #<Keyword name: "d">]

keywords table has only two columns name and id.

Solution is

  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(s开发者_如何转开发ql)
  end


The problem is that your Keyword model doesn't know what count_value is and you're instantiating a bunch of Keyword instances based on an SQL query. When your instances are created, they see count_value in the data they're handed but they ignore it as they have no count_value property.

If you want to run arbitrary SQL and get back simple data, you should be using select_rows or similar low level methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消