Hartator
Hartator

Reputation: 5145

Best rails way to implement custom validations?

I am looking for the best way to implement custom validations. I am aware of this :

validates :email, :uniqueness => {:scope => :user_id}

It works perfect. But, I want to do something like this (fictive case but it illustrates well) :

validates :email, :uniqueness => {:scope => 'user.name'}

I am thinking of using customs validations like explained here on rails cast but it seems a little overkill to use a module for this.

Anyone ?

Upvotes: 0

Views: 151

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176392

Use a validation method.

class Model

  validate :validate_email_with_scope

  private

    def validate_email_with_scope
      if Model.where(...).any?
        errors.add(:email, 'is not unique')
      end
    end

end

Replace Model.where(...).any? with your query.

Upvotes: 3

Related Questions