我想在我实际发送电子邮件时验证email
对象,而不是每次我更新时都验证:
class Email < ActiveRecord::Base
# Runs on every update/save method
validates :body, presence: true
def send_email
# Only run when this method is called
if body.blank?
errors.add :body, "can't be blank"
raise ActiveRecord::InvalidRecord.new(self)
end
update_column(:sent_at, Time.zone.now)
EmailMailer.new_email(self).deliver
end
end
目前,此代码将在每次更新时验证body
,但我只想验证调用send_email
方法的时间。原因是我希望允许用户在不实际发送的情况下保存电子邮件,并且此验证会强制他们拥有值。
我可以在我的方法中手动检查验证,但是想知道是否有一个&#34;清洁剂&#34;接近这个,比如:
validates :body, presence: true, action: :send_email # does not work, but what I want
更新2015-08-13 15:30
我有一些半工作代码,但更喜欢比我更清晰的解决方案:
class Email < ActiveRecord::Base
# remove validate methods
def send_email
errors.add :body, "can't be blank" if body.blank?
# My application has some higher level controller code that handles exceptions.
raise ActiveRecord::InvalidRecord.new(self) if errors.any?
# code execution should be stopped by exception...
end
end