我的has_many:通过Releases / Products / Tracks上的关联似乎是在releases_tracks / products_tracks表中删除Track和离开的孤立关联。我无法看到我出错的地方,我认为默认行为是仅删除关联。有人可以帮忙吗?
我的模特:
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 %>
答案 0 :(得分: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
s:
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