Rails 3.1 - 查找使用计数并选择为

Ale*_*lex 9 activerecord ruby-on-rails ruby-on-rails-3.1

我试图在rails中执行以下sql语句:

SELECT COUNT(downloads.title) AS total, downloads.title FROM `downloads` WHERE `downloads`.`member_id` = 60 Group by `downloads`.`title`
Run Code Online (Sandbox Code Playgroud)

我在这样的rails中写了这个:

Download.where(:member_id => id).select("COUNT(downloads.title) AS total, downloads.title").group(:title)
Run Code Online (Sandbox Code Playgroud)

如果我直接从sql服务器运行查询sql正确执行但如果我运行activerecord版本我只返回标题.

我认为这可能是因为attr_accessible,但这似乎没有什么区别.

有任何想法吗 ?

Bit*_*rse 16

您是否尝试total在集合对象上调用方法?
对象使用to_s方法的输出中不包含此信息,因此您可能只是看不到它,但总值是存在的.

downloads = Download.where(:member_id => id).select("COUNT(downloads.title) AS total, downloads.title").group(:title)
downloads.first.total
Run Code Online (Sandbox Code Playgroud)