0

我的 has_many :through 对 Releases/Products/Tracks 的关联似乎正在删除 Track 并在 release_tracks / products_tracks 表中留下孤立的关联。我看不出哪里出错了,我认为默认行为是仅删除关联。有人可以帮忙吗?

我的模型:

 class Track < ActiveRecord::Base
   has_many :releases_tracks
   has_many :tracks, :through => :releases_tracks

   has_many :products_tracks
   has_many :products, :through => :products_tracks 
 end

 class Release < ActiveRecord::Base
   has_many :releases_tracks
   has_many :tracks, :through => :releases_tracks
 end

 class Product < ActiveRecord::Base
   has_many :products_tracks
   has_many :tracks, :through => :products_tracks
   before_save do
     self.track_ids = self.releases_track_ids
   end
 end

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

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

我的轨道控制器(用于销毁操作):

 class TracksController < ApplicationController
  before_filter :get_track_parent

 def destroy
   @track = @parent.tracks.find(params[:id])
   @track.destroy
   redirect_to @parent  
 end

 private

 def get_track_parent
   if params[:product_id].present?
   @parent = Product.find(params[:product_id])
   elsif params[:release_id].present?
   @parent = Release.find(params[:release_id])
   end
 end
 end

我在发布视图中的销毁链接:

 <%= link_to image_tag("icons/delete.png"), release_track_path(@release,track), :confirm => 'Are you sure?', :method => :delete %>

最后,我在产品视图中的销毁链接:

 <%= link_to image_tag("icons/delete.png"), product_track_path(@product,track), :confirm => 'Are you sure?', :method => :delete %>
4

1 回答 1

1

首先,您需要:dependent => :destroy为您的关联选择:

class Track < ActiveRecord::Base
  has_many :releases_tracks, :dependent => :destroy
  has_many :releases, :through => :releases_tracks # also note you had here :tracks instead of :releases

  has_many :products_tracks, :dependent => :destroy
  has_many :products, :through => :products_tracks 
end

此外,如果您希望在删除版本或产品时删除曲目,请添加以下内容:dependent => :destroy

class Release < ActiveRecord::Base
  has_many :releases_tracks, :dependent => :destroy
  has_many :tracks, :through => :releases_tracks
end

class Product < ActiveRecord::Base
  has_many :products_tracks, :dependent => :destroy
  has_many :tracks, :through => :products_tracks
  before_save do
    self.track_ids = self.releases_track_ids
  end
end

class ProductsTrack < ActiveRecord::Base
  belongs_to :product
  belongs_to :track, :dependent => :destroy
end

class ReleasesTrack < ActiveRecord::Base
  belongs_to :release
  belongs_to :track, :dependent => :destroy
end
于 2012-04-04T16:19:36.610 回答