Raoot
Raoot

Reputation: 1771

Create and destroy HABTM associations - not actual records?

This is similar to a previous question, but our approach has changed a little since.

I need to be able to destroy the associations between Releases & Tracks + Products & Tracks without destroying the track itself. I need to then be able to re-associate a Track with any Release or Product.

My models are as follows:

 class Release < ActiveRecord::Base
   has_many :products, :dependent => :destroy
   has_and_belongs_to_many :tracks
 end

 class Product < ActiveRecord::Base
   belongs_to :release
   has_many :releases_tracks, :through => :release, :source => :tracks      
   has_and_belongs_to_many :tracks
   before_save do
   self.track_ids = self.releases_track_ids
   end        
 end

class Track < ActiveRecord::Base
  has_and_belongs_to_many :releases
  has_and_belongs_to_many :products
end

class ReleaseTracks < ActiveRecord::Base
  belongs_to :release
  belongs_to :track
end

class ProductsTracks < ActiveRecord::Base
  belongs_to :product
  belongs_to :track
end

Can anyone help with the appropriate controller methods please?

If I use the following on a Product Track for example, it destroys the track and association:

 @product = Product.find(params[:product_id])
 @track = @product.tracks.find(params[:id])
 @track.destroy

I've tried something like this but it gives me a notmethoderror:

 @product = Product.find(params[:product_id])
 @track = @product.products_tracks.find(params[:track_id])
 @track.destroy

Can anyone point me in the right direction? As I say, I need this primarily on destroy, but i also need to then be able to re-create associations.

Upvotes: 1

Views: 1942

Answers (1)

Tom Harrison
Tom Harrison

Reputation: 14028

has_and_belongs_to_many (HABTM) is one way of declaring a many-to-many relationship between two models. Under the covers, rails uses a simple join table (a table with two columns only, each a foreign key to the primary key of the main tables). The association exists when a record in the join table exists. I am not sure how destroy works by default in this case, but it may decide to delete all of the associated records (not just the association). You may be able to control this by using the dependent <action> clause on the HABTM declaration. The relationship is created when you assign one or more "children" to a parent and save.

In this case, maybe what you want is a pair of has_many :through relations -- the "through" is a relation, but can be treated as a first class model, and extended and operated on with ActiveRecord, meaning you can get at a specific release track (for example) and decide to delete it without affecting either association.

There's a good section on when to use one vs. the other in this Rails Guide: http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

Upvotes: 1

Related Questions