Search code examples
ruby-on-railsrubyvalidationmodelblacklist

Rails custom e-mail validator | Blacklist


Situation:

I got a user model, which needs to be validated by a list of blacklisted e-mail addresses. The blacklisted e-mail addresses are located in an extra model called blacklist

models/user.rb:

    class User < ActiveRecord::Base
            validate :email_is_not_blacklisted

            def email_is_not_blacklisted
                    @blacklist = Blacklist.where(:blacklist_type => "E-Mail")

                    @blacklist.each do |item|
                            errors.add(:email, 'is blacklisted') if self.email.match(item)
                    end
            end
    end

models/blacklist.rb

    class Blacklist < ActiveRecord::Base
            attr_accessible :name, :blacklist_type

            #some validation code for blacklist items ...
    end

Blacklist entry examples

    #:        name,            blacklist_type
    #1:       'demo-mail.com', 'E-Mail'
    #2:       'test123.com',   'E-Mail'

The blacklist model also will be used to ban specific usernames in the future!

Problem:

My problem is that [at]blacklist is always nil. Maybe there is something wrong with my logic? In other words: is it possible to access a model inside another model without an accosiation anyway?

Thanks for your help in advance and apologies existing language faults. I'm not a native english speaker :)

SOLUTION! I missed to define which attribute of the item should be used ...

    errors.add(:email, 'is blacklisted') if self.email.match(item.name)

Sometimes my brain doesn't like the way I like ...


Solution

  • I will suggest you to use this

    class User < ActiveRecord::Base
      validate :email_is_not_blacklisted
    
      def email_is_not_blacklisted
        if Blacklist.find_by_blacklist_type_and_name("E-Mail",self.email)
           errors.add(:email, 'is blacklsited') 
        end
      end
    end
    

    this will be faster then the previous ones