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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8048987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:19:13  来源:igfitidea点击:

Rails 3.1 - find using count and select as

ruby-on-railsactiverecordruby-on-rails-3.1

提问by Alex

I am trying to do the following sql statement in rails:

我正在尝试在 Rails 中执行以下 sql 语句:

SELECT COUNT(downloads.title) AS total, downloads.title FROM `downloads` WHERE `downloads`.`member_id` = 60 Group by `downloads`.`title`

I wrote this in rails like this:

我在 Rails 中这样写:

Download.where(:member_id => id).select("COUNT(downloads.title) AS total, downloads.title").group(:title)

If I run the query straight from the sql server the sql executes correctly but if I run the activerecord version I only get the title back.

如果我直接从 sql server 运行查询,sql 会正确执行,但如果我运行 activerecord 版本,我只会得到标题。

I thought this might be because of attr_accessible but this doesnt seem to have made a difference.

我认为这可能是因为 attr_accessible ,但这似乎没有什么不同。

any ideas ?

有任何想法吗 ?

回答by BitOfUniverse

Have you tried to call totalmethod on the collection object ?
This information is not included in the output for object using to_smethod, so you probably just do not see it, but total value is there.

您是否尝试过total在集合对象上调用方法?
此信息不包含在对象 usingto_s方法的输出中,因此您可能只是看不到它,但总价值在那里。

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