1

I have two models (and tables) in my Rails project. Each model has an "Address" field.

Currently, I have my code set to validate the uniqueness of the Address in each model, and on each table there is an index for the Address to prevent duplicates in the case of multiple connections trying to save the same data.

However, I would like to ensure that the Address field is unique across the two tables. As in, if the Address exists in one table, it could not be saved into the second table.

Solving that in code isn't that tough, but how would I implement that check at the database level (similar to an index) to ensure that no non-unique values are ever saved?

Bryce
  • 2,802
  • 1
  • 21
  • 46
  • 1
    If your question is about «database level» I suggest you to update your tags and title and specify your DBMS. If it's MySQL then — http://stackoverflow.com/questions/1452097/implementing-unique-across-linked-tables-in-mysql. But I'd rather solve this with custom validation method — extremely simple. – jibiel Sep 27 '12 at 05:04
  • Your database design is wrong. http://en.wikipedia.org/wiki/Database_normalization – Dondi Michael Stroma Sep 27 '12 at 08:03

2 Answers2

2

You'd be best off creating an Address table which can be responsible for maintaining uniqueness on its own. Rather than maintaining an address field on your other models, provide an association instead. It could be done as follows:

class Home < ActiveRecord::Base
  belongs_to :address
end

class Office < ActiveRecord::Base
  belongs_to :address
end

class Address < ActiveRecord::Base
  attr_accessible :body
  validates :body, uniqueness: true

  has_many :homes
  has_may :offices
end
rossta
  • 11,394
  • 1
  • 43
  • 47
  • I'm familiar with associations, but that's not going to work for me in this case. Is there any way to solve the problem as I've stated it? – Bryce Sep 27 '12 at 03:53
0

Write custom validators in both tables. custom validation rails guide is the excellent place to start. In the custom validator you can raise errors if that value is already there in another tables address field.

aadilcifer
  • 16
  • 2
  • I was really hoping that I could also enforce this uniqueness at the database level, but I suppose that custom validation is going to be the best I can do. – Bryce Sep 28 '12 at 03:50