Panagiotis
Panagiotis

Reputation: 421

How to validate the uniqueness of attribute in two models in Rails?

I have 2 models, University and Company, both of which have a name attribute. I am using the mailboxer gem so that both can act as messagable. My problem is that after I added auto-complete for the recipient of a message, I realized that the only value I have to find where I have to send the message is the name of the university or the company.

So now I am trying to enforce uniqueness of this attribute for both models. Is this possible and if yes, how?

Upvotes: 0

Views: 144

Answers (2)

Ruby Racer
Ruby Racer

Reputation: 5740

You should use a custom validation, like:

company.rb

validates :name, uniqueness: true
validate :name_not_on_universities

private
def name_not_on_universities
    uname=University.where(:name => self.name).first
    uname.nil?
end

and similarly for the other model

Upvotes: 3

Amr Arafat
Amr Arafat

Reputation: 489

One way to do it is to use inheritance. You can have something like this:

Whatever.rb

Class Whatever < ActiveRecord::Base
....
validates :name, uniqueness: true

Company.rb

Class Company < Whatever

University.rb

Class University < Whatever

Upvotes: 0

Related Questions