如何使用Ruby on Rails查询结果集大小?
- 内容介绍
- 相关推荐
本文共计305个文字,预计阅读时间需要2分钟。
在Rails中,你可以使用以下查询来获取特定条件下的记录:
rubyrecords=Record.select('y_id, source').where(source: source, y_id: y_id).group(:y_id, :source).having('count(*)=1')
如果设置了记录,你将得到以下输出:
ruby[...]
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,它将返回一个整数.
本文共计305个文字,预计阅读时间需要2分钟。
在Rails中,你可以使用以下查询来获取特定条件下的记录:
rubyrecords=Record.select('y_id, source').where(source: source, y_id: y_id).group(:y_id, :source).having('count(*)=1')
如果设置了记录,你将得到以下输出:
ruby[...]
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,它将返回一个整数.

