【发布时间】:2014-04-16 19:42:21
【问题描述】:
嗯,我有这个模型的简化版(Rails 3.2.13):
class Transfer < ActiveRecord::Base
attr_accessible :from,:to,:total
validates_presence_of :from,:to,:total
before_validation :positive_numbers, on: :create
before_validation :check_enough_balance, on: :create
after_validation :update_balances
private
def positive_numbers
unless self.total>0
errors.add(:total,"should be greater than 0")
return false
end
end
def check_enough_balance
@sender=User.find(self.from)
@receiver=User.find(self.to)
unless @sender.enough_balance(self.total)
errors.add(:base,"Not enough credit")
return false
end
end
def update_balances
@sender.balance -= self.total
@receiver.balance += self.total
@sender.save
@receiver.save
end
def another_action
puts 'does something'
end
end
每当total<0,实例返回false,errors 数组正确填充,another_action 回调不会被调用。
我想知道如何使用 Rails 的内置验证助手来获得相同的行为,这就是我尝试过的方法:
class Transfer < ActiveRecord::Base
attr_accessible :from,:to,:total
validates_presence_of :from,:to,:total
validates_numericality_of :total, greater_than: 0
before_validation :check_enough_balance, on: :create
after_validation :update_balances
private
def check_enough_balance
@sender=User.find(self.from)
@receiver=User.find(self.to)
unless @sender.enough_balance(self.total)
errors.add(:base,"Not enough credit")
return false
end
end
def update_balances
@sender.balance -= self.total
@receiver.balance += self.total
@sender.save
@receiver.save
end
end
class User<ActiveRecord::Base
attr_accessible :username
validates_presence_of :username, :balance
def enough_balance(amount)
self.balance >= amount
end
end
但是在这种情况下,由于验证助手没有 return false 调用以下自定义验证 check_enough_balance,我希望它的行为完全相同,并且我相信使用验证助手在某种程度上更加优雅和简洁。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 validation