Has many, belongs to relationship allowing duplicates


#1

Hi all,

I have a couple of tables setup as follows:

(1) User table (general user info)

(2) Subsriptions table
id
user_id <- links to User.id
subscriber_id <- links to User.id

Basically a user can have one or more subscribers. Subscribers being
other users.

User has the following:

has_many :subscribers,
:class_name => ‘Subscription’

Subscription model has:

belongs_to :user,
:class_name => ‘User’

Is there anyway that I can setup a relationship like this, with these
two tables, having a user that has subscribers, but disallow
duplicates in the subscriptions table?

Because when I do something line the following:

u = User.find(1)
s = Subscription.new
s.user_id = 1
s.subscriber_id = 3
u.subscribers << 2

I end up with the following records in the subscriptions table:

id user_id subscriber_id
1 1 3
2 1 3

Record with id = 1 was there before the above code was run. How can I
set thiings up so that if I add a subscriber that already exists for a
particular user, it doesn’t add a duplicate record. Would be nice if
it doesn’t complain about trying to add one either and just does
nothing if it’s already there. Maybe that’s asking too much?

Any help would be greatly appreciated.

Thanks in advance.

Cheers,
Diego


#2

Diego,

Take a look at validates_uniqueness_of. Something like this should
get you started:

class Subscription < ActiveRecord::Base
validates_uniqueness_of :user_id, :scope => :subscriber_id
end

Validations will prevent a record from being saved and attach error
information to the object. What you do with that information is your
decision.

Aaron


#3

Hi Arron,

Thanks for the pointers. I’ll follow along and try these out.
Appreciate it!

Cheers,
Diego


#4

other users.

Is there anyway that I can setup a relationship like this, with these
two tables, having a user that has subscribers, but disallow
duplicates in the subscriptions table?

has_many has a :uniq option that might help you out…

:uniq - if set to true, duplicates will be omitted from the collection.
Useful in conjunction with :through.