How to find size of query result

不羁岁月 提交于 2020-01-02 07:04:11

问题


I have the following query in rails:

records = Record.select('y_id, source')
                .where(:source => source, :y_id => y_id)
                .group(:y_id, :source)
                .having('count(*) = 1')

I get the following output if I puts records:
[#<Record source: "XYZ", y_id: 10000009>, #<Record source: "XYZ", y_id: 10000070>]

This looks like there are 2 elements in the output array. But when I try to do records.size I get:
{[10000009, "XYZ"]=>1, [10000070, "XYZ"]=>1}

  • Why doesn't records.size print 2 when records is an array having 2 elements? Is the group by query result behaving differently for some reason?

  • What should I do to get the size of records


回答1:


I could be on the wrong track but I think the issue is to do with the way .size works.

Size will automatically try to determine whether to call .count or .length. These behave in the followings ways:

  • .count performs a SQL COUNT
  • .length calculates the length of the resultant array

However on occassion .size will return a hash (as it has decided to use .count)

So your solution may be to use .length which will return an integer.




回答2:


You can get it using :

results.length

The size method uses the sql count method which behaves this way.




回答3:


I just tried a variant on the above example (using my own existing Rails app and DB) and it worked without issues:

records = Site.select('name','url')
    .where(:name => 'Washington Post', :url => 'https://www.washingtonpost.com/')
    .group(:name, :url)
    .having('count(*) = 1')

 => #<ActiveRecord::Relation [#<Site id: nil, name: "Washington Post", url: "https://www.washingtonpost.com/">]> 

records.size

 => 1 

Are you sure your Record model inherits from ActiveRecord::Base?



来源:https://stackoverflow.com/questions/34540762/how-to-find-size-of-query-result

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