Rails选择GROUP

时间:2015-07-24 19:57:24

标签: ruby-on-rails ruby-on-rails-4

目标是选择最常用Store的{​​{1}}。

目前,我有这个,它有效(分解为解释):

Coupon

它的使用方式如下:

# coupon.rb
  has_many :redemptions
  has_and_belongs_to_many :stores

  def most_popular_store
    stores.find(        # Return a store object
      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
      .keys             # Create an array of keys
      .sort             # Sort the keys so highest is first
      .first            # Take the ID of the first key
    )
  end
###

就像我说的那样,该方法有效,但它看起来像monkeypatched。我怎样才能重构我的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 方法?

1 个答案:

答案 0 :(得分:2)

我认为你的方法实际上并不起作用。 count为您提供一个哈希,其键为store_ids,值为计数,然后您在哈希上运行keys,这将为您提供store_ids数组。从那时起,你已经失去了计数,你正在按store_ids排序并抓住第一个。您的测试通过的唯一原因是您在另一个之前创建了受欢迎的商店,因此它获得了较低的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)