query , can not select column count

こ雲淡風輕ζ 提交于 2019-12-17 05:14:22

问题


Tag.joins(:quote_tags).group('quote_tags.tag_id').order('count desc').select('count(tags.id) AS count, tags.id, tags.name')

Build query:
SELECT count(tags.id) AS count, tags.id, tags.name FROM `tags` INNER JOIN `quote_tags` ON `quote_tags`.`tag_id` = `tags`.`id` GROUP BY quote_tags.tag_id ORDER BY count desc

Result:

[#<Tag id: 401, name: "different">, ... , #<Tag id: 4, name: "family">]

It not return count column for me. How can I get it?


回答1:


Have you tried calling the count method on one of the returned Tag objects? Just because inspect doesn't mention the count doesn't mean that it isn't there. The inspect output:

[#<Tag id: 401, name: "different">, ... , #<Tag id: 4, name: "family">]

will only include things that the Tag class knows about and Tag will only know about the columns in the tags table: you only have id and name in the table so that's all you see.

If you do this:

tags = Tag.joins(:quote_tags).group('quote_tags.tag_id').order('count desc').select('count(tags.id) AS count, tags.id, tags.name')

and then look at the counts:

tags.map(&:count)

You'll see the array of counts that you're expecting.




回答2:


Update: The original version of this answer mistakenly characterized select and subsequent versions ended up effectively repeating the current version of the other answer from @muistooshort. I'm leaving it in it's current state because it has the information about using raw sql. Thanks to @muistooshort for pointing out my error.

Although your query is in fact working as explained by the other answer, you can always execute raw SQL as an alternative.

There are a variety of select_... methods you can choose from, but I would think you'd want to use select_all. Assuming the build query that you implicitly generated was correct, you can just use that, as in:

ActiveRecord::Base.connection.select_all('
  SELECT count(tags.id) AS count, tags.id, tags.name FROM `tags`
    INNER JOIN `quote_tags` ON `quote_tags`.`tag_id` = `tags`.`id`
    GROUP BY quote_tags.tag_id
    ORDER BY count desc')

See http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html for information on the various methods you can choose from.



来源:https://stackoverflow.com/questions/18350632/query-can-not-select-column-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!