Forum: Ruby on Rails has many, belongs to relationship allowing duplicates...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Diego (Guest)
on 2007-02-16 08:08
(Received via mailing list)
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
Aaron (Guest)
on 2007-02-16 08:37
(Received via mailing list)
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
Diego (Guest)
on 2007-02-16 08:40
(Received via mailing list)
Hi Arron,

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

Cheers,
Diego
Philip H. (Guest)
on 2007-02-16 18:36
(Received via mailing list)
> 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.
This topic is locked and can not be replied to.