我有这种方法(self.invoice_magistrates),它可以开具满足特定标准的现有成员,即。他们是活跃会员,并事先付款。
问题在于elsif行:( elsif!magistrate.payments.last.paid_this_month?)即使这是假的,它仍会创建付款,。
我有一个正常运行的类似方法(self.invoice_judges)。希望你能帮我谢谢。
//checks whether payment was made in the current month
def paid_this_month?
self.date.strftime("%B %Y") == Date.today.strftime("%B %Y")
end
//problematic code
def self.invoice_magistrates
count = 0
Member.magistrates.active.includes(:payments).each do |magistrate|
if magistrate.payments.empty?
deactivate_member(magistrate)
//even when false it still creates payment
elsif !magistrate.payments.last.paid_this_month?
count += 1
amount_to_pay = PaymentPlan.last.magistrate
magistrate.payments.create(:invoice => amount_to_pay, :amount => amount_to_pay, :balance => 0, :date => Time.now.to_date, :region => magistrate.region)
end
end
return count
end
//similar method that runs correctly although the members are less
def self.invoice_judges
count = 0
Member.judges.active.includes(:payments).each do |judge|
if judge.payments.empty?
deactivate_member(judge)
elsif !judge.payments.last.paid_this_year?
count += 1
amount_to_pay = PaymentPlan.last.judge
balance = judge.balance + amount_to_pay
judge.payments.create!(:date => Time.now.beginning_of_year.to_date, :invoice => amount_to_pay, :amount => 0, :balance => balance, :region => judge.region)
judge.update_column(:balance, balance)
end
end
return count
end
答案 0 :(得分:0)
尝试从| magistrate|
...
Member.magistrates.active.includes(:payments).each do |magistrate|
我可能会尝试使条件更具体,但是如果没有一组示例数据,则几乎不可能对正在发生的事情进行故障排除。
此外,阅读elsif !something?
非常不直观。你最好在模型上编写一个新方法,这样你就可以elsif not_something?
def self.invoice_magistrates
count = 0
Member.magistrates.active.includes(:payments).each do |magistrate|
if magistrate.payments.empty?
deactivate_member(magistrate)
elsif magistrate.unpaid_this_month?
count += 1
amount_to_pay = PaymentPlan.last.magistrate
magistrate.payments.create(:invoice => amount_to_pay, :amount => amount_to_pay, :balance => 0, :date => Time.now.to_date, :region => magistrate.region)
end
end
return count
end
如果您认为不应该付款,那么您使用的数据不是您认为的那样,或者这种逻辑不正确:!magistrate.payments.last.paid_this_month?
答案 1 :(得分:0)
Member.magistrates.active.includes(:payments)
includes()不保证任何订购
magistrate.payments.last
并不总是返回上次付款。