cgriego/active_attr — Issue #81: before_validation and validate method.
Author: phstc
Created: 2012-03-05 23:41:02+00:00
State: open

Hey!

I created a kind of contact model that sends an e-mail in the method save. In my case I need to validate if the user wasn't unsubscribed the mail list before send it.

I tried

validate :find_or_create_user_with_success
and
before_validation :find_or_create_user_with_success

But they aren't called when I call puts_mail.save. Is there a way to integrate these custom validators with ActiveAttr?

require "email_format_validator"
class PutsMail
include ActiveAttr::Model

attribute :to
attribute :subject
attribute :body
attribute :user

validates :to, :presence => true, :email_format => true
validates :subject, :presence => true
validates :body, :presence => true

validate :find_or_create_user_with_success

def save
PutsMailer.puts_mail(self).deliver
Property.increment_mail_counter
end

private

def find_or_create_user_with_success
self.user = User.find_or_create_by_mail(self.to)
unless self.user.subscribed?
self.errors.add_to_base("the e-mail '#{self.to}' was unsubscribed the Puts Mail Test List. To subscribe it again, send an e-mail to subscribe@putsmail.com")
end
end
end

Cheers,
Pablo Cantero