我有以下模型:Releases
, Tracks
& 一个has_many
名为ReleasesTrack
.
我也有Product
s (半)成功地继承了发布曲目,其中 Track & Release Id 被复制到ProductsTrack
has_many_through 连接。
问题是我没有得到正确的位置值。
我目前有这个ProductsTrack
模型,它似乎工作,但我没有得到我想要的价值。
before_save do
self.position = self.track.position
end
我想要的是 has_many_through 连接表 release_tracks 中的位置,而不是轨道表中的位置值。我尝试了以下变体,但没有任何乐趣:
before_save do
self.position = self.track.releases_track.position
end
我确实认为在 Tracks 和 ReleasesTracks 中都有一个位置字段可能会导致问题,并且我在两者中都有这个原因是有原因的,但是我已经使用临时字段进行了测试,但事实并非如此。
我认为问题的症结在于结构self.track.releases_track.position
正确。
或者
我在协会中遗漏了一些东西?
有任何想法吗?
编辑:模型添加(注意,ProductsTrack 实际上是名字不好的 Producttracklisting)
class Release < ActiveRecord::Base
has_many :products, :dependent => :destroy
has_many :releases_tracks, :dependent => :destroy, :after_add => :position_track
has_many :tracks, :through => :releases_tracks, :order => "releases_tracks.position"
accepts_nested_attributes_for :tracks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
accepts_nested_attributes_for :releases_tracks
def position_track(track)
releases_tracks.each { |t| t.position = t.track.position }
end
def track_attributes=(track_attributes)
track_attributes.each do |attributes|
tracks.build(attributes)
artists_tracks.build(attributes)
end
end
end
class Track < ActiveRecord::Base
has_many :releases_tracks, :dependent => :destroy
has_many :releases, :through => :releases_tracks
has_many :producttracklistings, :dependent => :destroy
has_many :products, :through => :producttracklistings
end
class ReleasesTrack < ActiveRecord::Base
belongs_to :release
belongs_to :track
end
class Producttracklisting < ActiveRecord::Base
belongs_to :product
belongs_to :track
before_save do
self.position = self.track.position
end
end
class Product < ActiveRecord::Base
belongs_to :release
has_many :releases_tracks, :through => :release, :source => :tracks
has_many :producttracklistings, :dependent => :destroy
has_many :tracks, :through => :producttracklistings
accepts_nested_attributes_for :tracks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
accepts_nested_attributes_for :producttracklistings
#Below is where a product inherits tracks from the parent release
before_save do
self.track_ids = self.releases_track_ids
end
end