将档案的sql转换为Rails ActiveRecord

时间:2017-09-19 10:21:57

标签: sql ruby-on-rails rails-activerecord

我在Post模型中有这个类方法用于存档

class Post < ActiveRecord::Base
  def self.archives
    # fetch archives
  end
end

如何将此sql查询转换为ActiveRecord查询以将其置于self.archives方法中?

SELECT YEAR(`created_at`) AS `year`, MONTHNAME(`created_at`) AS `month`, COUNT(`id`) AS `total` 
FROM `posts` 
GROUP BY `year`, `month` 
ORDER BY `year` DESC, MONTH(`published_at`) DESC

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

def self.archives
  Post.select("YEAR(created_at) AS year, MONTHNAME(created_at) AS month, COUNT(id) AS total")
    .group("year, month")
    .order("year DESC, MONTH(published_at) DESC")
end