malcom
malcom

Reputation: 25

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 ...

Upvotes: 1

Views: 1282

Answers (3)

Aayush Khandelwal
Aayush Khandelwal

Reputation: 1071

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

Upvotes: 3

mhutter
mhutter

Reputation: 2916

To expand on my comment, try this:

class User < ActiveRecord::Base
  validate :email_is_not_blacklisted

  def email_is_not_blacklisted
    Blacklist.find_all_by_blacklist_type("E-Mail").each do |item|
      errors.add(:email, 'is blacklsited') if.self.email.match(item)
    end
  end
end

Upvotes: 0

Yule
Yule

Reputation: 9764

Case sensitivity. You're searching for blacklist-type = "E-Mail" and your example data is "e-mail"

Upvotes: 0

Related Questions