Validate uniqueness of multiple columns

re5et picture re5et · Feb 2, 2011 · Viewed 70.4k times · Source

Is there a rails-way way to validate that an actual record is unique and not just a column? For example, a friendship model / table should not be able to have multiple identical records like:

user_id: 10 | friend_id: 20
user_id: 10 | friend_id: 20

Answer

Dylan Markow picture Dylan Markow · Feb 2, 2011

You can scope a validates_uniqueness_of call as follows.

validates_uniqueness_of :user_id, :scope => :friend_id