Bryce
Bryce

Reputation: 2872

ActiveRecord - Prevent duplicate entries across tables

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?

Upvotes: 1

Views: 1336

Answers (2)

aadilcifer
aadilcifer

Reputation: 16

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.

Upvotes: 0

rossta
rossta

Reputation: 11494

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

Upvotes: 2

Related Questions