我在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
答案 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