目标是选择Store
其中一个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
###
它的用法如下:
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
就像我说的,这个方法是有效的,但它看起来像是经过猴子补丁的。我怎样才能重构我的most_popular_store
method?
我觉得你的方法其实行不通。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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)