问题
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
print2
when records is an array having 2 elements? Is thegroup 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