Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails选择组中计数最高的对象_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails Rails选择组中计数最高的对象

Ruby on rails Rails选择组中计数最高的对象,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,目标是选择商店,其中优惠券最常用 目前,我有这个,并且它可以工作(分解以进行解释): 它是这样使用的: describe 'most_popular_store' do it 'returns the most popular store' do # Create coupon coupon = FactoryGirl.create(:coupon) # Create two different stores most_p

目标是选择
商店
,其中
优惠券
最常用

目前,我有这个,并且它可以工作(分解以进行解释):

它是这样使用的:

describe 'most_popular_store' do
    it 'returns the most popular store' do
        # Create coupon
        coupon = FactoryGirl.create(:coupon)

        # Create two different stores
        most_popular_store = FactoryGirl.create(:store, coupons: [coupon])
        other_store        = FactoryGirl.create(:store, coupons: [coupon])

        # Add redemptions between those stores
        FactoryGirl.create_list(:redemption, 2, coupon: coupon, store: other_store)
        FactoryGirl.create_list(:redemption, 5, coupon: coupon, store: most_popular_store)

        # Verify
        expect(coupon.most_popular_store.title).to eq most_popular_store.title
    end
end

正如我所说的,这个方法是有效的,但它看起来有缺陷。我如何重构我的
最流行的
存储方法?

我认为你的方法实际上不起作用
count
提供一个散列,其中键作为存储ID,值作为计数,然后对散列运行
keys
,这将为您提供一个存储ID数组。从那时起,您将丢失计数,您将按存储单元ID进行排序并获取第一个。您的测试通过的唯一原因是您在创建另一个流行存储之前创建了它,因此它会得到一个较低的id(
sort
默认情况下进行升序排序)。要获得正确的结果,请进行以下更改:

redemptions       # Start with all of the coupon's redemptions
  .group(:store_id) # Group them by the store_id
  .count            # Get a hash of { 'store_id' => 'count' } values
  .max_by{|k,v| v}  # Get key, val pair with the highest value
                    # output => [key, value]
  .first            # Get the first item in array (the key)

你可以使用counter_cache进行赎回,这样你就不必加入了。你说的“它看起来像蒙基补丁”是什么意思?你是在寻找一个单一的查询,还是一个“看起来不错”的查询?@eirikir我的意思是,排序和ID选择似乎可以在查询中处理,而不是在下拉记录后处理。效果很好!看起来还是有点长,但它确实比我以前做的更好!谢谢
redemptions       # Start with all of the coupon's redemptions
  .group(:store_id) # Group them by the store_id
  .count            # Get a hash of { 'store_id' => 'count' } values
  .max_by{|k,v| v}  # Get key, val pair with the highest value
                    # output => [key, value]
  .first            # Get the first item in array (the key)