我们有一个模型Partner
。该合作伙伴销售accounts
。每个月我们会根据帐户数量重新计算一些内容。我想避免在多个模型方法中重复相同的计数,实际上是相同的多个“if”条件,但需要能够单独运行它们,那么如何干掉代码呢?
我在想我可以把它们放在一个数组中,然后用相关方法引用它,但不知道如何继续。这就是目前的样子......
def recalculate_kickback
accounts = self.accounts.count
if accounts == 0
self.update_attribute(:kickback, 0)
elsif accounts.between?(1,5)
self.update_attribute(:kickback, 10)
elsif accounts.between?(5,15)
self.update_attribute(:kickback, 15)
else
self.update_attribute(:kickback, 30)
end
end
def recalculate_level
accounts = self.accounts.count
if accounts == 0
self.update_attribute(:partner_level, 'None')
elsif accounts.between?(1,5)
self.update_attribute(:partner_level, 'Bronze')
elsif accounts.between?(5,15)
self.update_attribute(:partner_level, 'Silver')
else
self.update_attribute(:partner_level, 'Gold')
end
end
答案 0 :(得分:4)
您可以使用常量定义“级别”:
LEVEL_NONE = { kickback: 0, name: 'None' }.freeze
LEVEL_BRONZE = { kickback: 10, name: 'Bronze' }.freeze
LEVEL_SILVER = { kickback: 15, name: 'Silver' }.freeze
LEVEL_GOLD = { kickback: 30, name: 'Gold' }.freeze
根据帐户数量编写一个返回当前级别的方法:
def current_level
case accounts.count
when 0 then LEVEL_NONE
when 1..5 then LEVEL_BRONZE
when 5..15 then LEVEL_SILVER
else LEVEL_GOLD
end
end
并在方法中使用返回的哈希:
def recalculate_kickback
update_attribute(:kickback, current_level[:kickback])
end
def recalculate_level
update_attribute(:partner_level, current_level[:name])
end
答案 1 :(得分:0)
请尝试以下操作。
你可以有两种不同的方法recalculate_kickback和recalculate_level或者你可以有一个方法,比如recalculate_kickback_and_level,它可以同时进行两次更新。
我希望它可以帮到你。
def recalculate_kickback
kickback = 30
accounts = self.accounts.count
case accounts
when 0
kickback = 0
when 1..5
kickback = 10
when 5..15
kickback = 15
else
kickback = 30
end
self.update_attribute(:kickback => kickback)
end
def recalculate_level
partner_level = 'Gold'
accounts = self.accounts.count
case accounts
when 0
partner_level = 'None'
when 1..5
partner_level = 'Bronze'
when 5..15
partner_level = 'Silver'
else
partner_level = 'Gold'
end
self.update_attribute(:partner_level => partner_level)
end
def recalculate_kickback_and_level
kickback = 30
partner_level = 'Gold'
accounts = self.accounts.count
case accounts
when 0
kickback = 0
partner_level = 'None'
when 1..5
kickback = 10
partner_level = 'Bronze'
when 5..15
kickback = 15
partner_level = 'Silver'
else
kickback = 30
partner_level = 'Gold'
end
self.update_attributes(:kickback => kickback, :partner_level => partner_level)
end