Forum: Ruby on Rails Checking if an association already exists between two records

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.
294809707d8ef84c3da34cb6afb59d7e?d=identicon&s=25 Gearóid O'Ceallaigh (Guest)
on 2008-12-01 17:09
(Received via mailing list)
Hey,

I'm creating an app which has two models - bands and users. A
relationship between users and bands in many to many.

However, when I'm adding an existing to user to a band (ie. updating
the bands_users table) how can i check if the relationship between the
user and the band already exists? For example, if a user with ID of 3
was already a member of a band with ID 5, and then somebody tried to
make this connection again - I want to output an error message. Is
there some special validation I can place in a bands_users.rb that
validated the uniqueness of the entire record?

Thanks,
  -ger
2d8132658d56e51f19ace1c68e48b6aa?d=identicon&s=25 Thorsten Mueller (thorsten)
on 2008-12-01 17:38
(Received via mailing list)
You can use the scopt attribute of validates_uniqueness_of
But this would require, that the intermediate table between
users/bands has it's own model

in this model (BandsUsers)
validates_uniqueness_of :user_id, :scope => band_id
4b1b339ee3f96d37aba2adfa3e03276e?d=identicon&s=25 Brandon Keepers (Guest)
on 2008-12-01 18:30
(Received via mailing list)
On Mon, Dec 1, 2008 at 11:07 AM, Gearóid O'Ceallaigh
<gearoid.k@gmail.com> wrote:
> make this connection again - I want to output an error message. Is
> there some special validation I can place in a bands_users.rb that
> validated the uniqueness of the entire record?

There is a :uniq option that will ignore duplicates:

  class Band < ActiveRecord::Base
    has_and_belongs_to_many :users, :uniq => true
  end

This won't raise an error, but it will prevent duplicate associations.
 Hope that Helps

Brandon
--
--------------------------------------------------------------------------------
Training by Collective Idea: Ruby on Rails training in a vacation
setting
http://training.collectiveidea.com — San Antonio, TX — Jan 20-23
10f7e00c1c5c60e2173995eb16f4ffc7?d=identicon&s=25 pepe (Guest)
on 2008-12-03 04:25
(Received via mailing list)
I guess you have your reasons but why not ignore the fact that the
relationship already existed? Does it really matter to let the user
know?

Pepe
This topic is locked and can not be replied to.