Ruby on Rails中如何查询结果集大小是多少?
- 内容介绍
- 相关推荐
本文共计308个文字,预计阅读时间需要2分钟。
在Rails中,如果你有以下查询:
rubyrecords=Record.select('y_id, source').where(source: source, y_id: y_id).group(:y_id, :source).having('count(*)=1')
并且你已设置记录,那么你将得到以下输出:
ruby[ # 结果数组,每个元素包含y_id和source的值]
我在rails中有以下查询:records = Record.select('y_id, source') .where(:source => source, :y_id => y_id) .group(:y_id, :source) .having('count(*) = 1')
如果我放置记录,我会得到以下输出:
[#<记录来源:“XYZ”,y_id:10000009>,#<记录来源:“XYZ”,y_id:10000070>]
这看起来像输出数组中有2个元素.但是当我尝试做record.size时,我得到:
{[10000009,“XYZ”] => 1,[10000070,“XYZ”] => 1}
我可能走错了路,但我认为问题与.size的工作方式有关.
Why doesn’t
records.sizeprint2when records is an array having 2 elements? Is thegroup byquery result behaving differently for some reason?What should I do to get the size of
records
Size将自动尝试确定是否调用.count或.length.这些行为如下:
> .count执行SQL COUNT
> .length计算结果数组的长度
然而,在occassion .size将返回一个哈希(因为它决定使用.count)
所以你的解决方案可能是使用.length,它将返回一个整数.
本文共计308个文字,预计阅读时间需要2分钟。
在Rails中,如果你有以下查询:
rubyrecords=Record.select('y_id, source').where(source: source, y_id: y_id).group(:y_id, :source).having('count(*)=1')
并且你已设置记录,那么你将得到以下输出:
ruby[ # 结果数组,每个元素包含y_id和source的值]
我在rails中有以下查询:records = Record.select('y_id, source') .where(:source => source, :y_id => y_id) .group(:y_id, :source) .having('count(*) = 1')
如果我放置记录,我会得到以下输出:
[#<记录来源:“XYZ”,y_id:10000009>,#<记录来源:“XYZ”,y_id:10000070>]
这看起来像输出数组中有2个元素.但是当我尝试做record.size时,我得到:
{[10000009,“XYZ”] => 1,[10000070,“XYZ”] => 1}
我可能走错了路,但我认为问题与.size的工作方式有关.
Why doesn’t
records.sizeprint2when records is an array having 2 elements? Is thegroup byquery result behaving differently for some reason?What should I do to get the size of
records
Size将自动尝试确定是否调用.count或.length.这些行为如下:
> .count执行SQL COUNT
> .length计算结果数组的长度
然而,在occassion .size将返回一个哈希(因为它决定使用.count)
所以你的解决方案可能是使用.length,它将返回一个整数.

