私は次のモデルを持っています:Releases
、Tracks
&has_many
と呼ばれる結合ReleasesTrack
。
またProduct
、(半)正常にリリーストラックを継承し、トラックとリリースIDがProductsTrack
has_many_through結合にコピーされていることもあります。
問題は、正しい位置の値を取得していないことです。
私は現在これをProductsTrack
モデルに持っています、それはうまくいくように見えます、しかし私は私が望む値を得ていません。
before_save do
self.position = self.track.position
end
トラックテーブルの位置の値の代わりに、has_many_through結合テーブルreleases_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