views:

109

answers:

1

Hey guys,

I have a simple model "Match" that is supposed to save the bi-directional link between two objects (of the same kind).

class Match < ActiveRecord::Base
  belongs_to :obj1, :class_name => "MyModel", :foreign_key => :obj1_id
  belongs_to :obj2, :class_name => "MyModel", :foreign_key => :obj2_id

...
end

The problem I have is that for each bi-directional Match that I discover I get two database entries. E.g. 1: obj1 -> obj2, 2: obj2 -> obj1

How can I use validates_uniqueness_of to avoid this here? I tried

validates_uniqueness_of :obj1_id, :scope => :obj2_id
validates_uniqueness_of :obj2_id, :scope => :obj1_id

but that didn't work.

A: 
validates_uniqueness_of :obj1_id, :scope => :obj2_id

def validate
  if find(:first, :conditions => { :obj1 => obj2, :obj2 => obj1 })
    errors.add_to_base("already exists")
  end
end

Pretty ugly. Add some unique database indexes.

Waseem