Topic: Deleting from an associative entity

Im not sure if this is where I should ask this question but here it goes:

I am trying to delete a record from an associative table and have been unable to find anything in the API or google to allow me to do this without an id. Does rails allow for this or do I need to denormalize my table?


Re: Deleting from an associative entity

What do you mean "associative table"?  Do you mean, one table that's associated with another?  Like, for example:

What type of association?  has_many?  has_one?  Can you give more details?

Re: Deleting from an associative entity

By associative table I am referring to a table that was created to eliminate a many to many relationship. Therefore it's pk is a combination of two fk's. In my use it is an interests table between a registrants table and an interest_types table. I was able to come up with the following workaround by accessing the controllers db connection but I would like to use the rails way if I can.

Interest.connection.execute('DELETE FROM interests WHERE registrant_id = '+@registrant_id +' and interest_type_id = '+ @interest_type_id +';')

Re: Deleting from an associative entity

It sounds like what you're trying to do is essentially a has_and_belongs_to_many (habtm), where

  has_and_belongs_to_many :interests


  has_and_belongs_to_many :registrants

In between the Interest table and the Registrant table would be what's called a "Join Table", named, in this case registrants_interests.  You don't need a model for registrants_interests; as long as you follow the naming convention, and use the above habtm declarations, ActiveRecord will do the magic for you.  At that point, you can do nifty things like:

reg = Registrant.find(123)
=> ["books", "movies", "music"]
reg.interests << Interest.find_by_name("shoes")

For more info, see: … gs_to_many … gs_to_many

Agile Web Development with Rails, Chapter 18

Re: Deleting from an associative entity

Alright, as a db guy I designed the db first without knowing about that feature. I guess a redesign is in order.


Re: Deleting from an associative entity

Not necessarily.  You can use the ActiveRecord magic with your existing schema, you just have to explain to it how your schema works.  Rails is all about convention over configuration.  So, if you follow the convention, you get a lot of stuff for free.  But, if you don't, you can still configure Rails to work.

The following link is the API spec for the has_and_belongs_to_many declaration.  It'll tell you all about the different ways to configure it. … gs_to_many