2
votes

i have trouble to user uniqness couples in my app...

I have users witch can be linked to so some contacts. I use a relation table to do my links (witch has a level attribute also - for different level of relations)

So i have users, contacts and relationships. My problem is that the couple contact_id and user_id has to be uniq (they can be linked only once).

contact.rb

has_many :relations, :dependent => :destroy

has_many :users, :through => :relations, :uniq => true

user.rb

has_many :relations, :dependent => :destroy

has_many :contacts, :through => :relations, :uniq => true

relation.rb

belongs_to :user

belongs_to :contact

I dont know if i have to use foreign_key or whatever, i just need something simple :)

cheers

2

2 Answers

1
votes

You can use the :scope option on your uniqueness validation. Something like validates_uniqueness_of :contact, :scope => :user means that for a given user, there won't be duplicate contacts. So if you validate each of your attributes scoped to the other one, I think it results in what you want. There might be a better way (that I obviously don't know though).

1
votes
class Relation < ActiveRecord::Base
      belongs_to :user
      belongs_to :contact
      validates_uniqueness_of :contact_id, :scope => :user_id

    end