代码(Rails 4.0.0)
class Track < ActiveRecord::Base has_many :artist_tracks has_many :owning_artists,-> { where(:artist_tracks => { :artistic_role_id => 1 }) },:through => :artist_tracks,:source => :artist end class ArtistTrack < ActiveRecord::Base belongs_to :artist belongs_to :track belongs_to :artistic_role end class Artist < ActiveRecord::Base has_many :artist_tracks has_many :tracks,:through => :artist_tracks end
寻找作品
# artist_tracks.artistic_role_id is properly set to "1" 2.0.0p195 :003 > Track.last.owning_artists Track Load (1.1ms) SELECT "tracks".* FROM "tracks" ORDER BY "tracks"."id" DESC LIMIT 1 Artist Load (0.8ms) SELECT "artists".* FROM "artists" INNER JOIN "artist_tracks" ON "artists"."id" = "artist_tracks"."artist_id" WHERE "artist_tracks"."artistic_role_id" = 1 AND "artist_tracks"."track_id" = $1 [["track_id",10]]
创建不起作用
# artist_tracks.artistic_role_id is totally missing from the INSERT 2.0.0p195 :005 > Track.create!(name: "test_name",lyrics: "test_lyrics",owning_artist_ids: [1]) Artist Load (1.3ms) SELECT "artists".* FROM "artists" WHERE "artists"."id" = $1 LIMIT 1 [["id",1]] (0.5ms) BEGIN Artist Exists (0.7ms) SELECT 1 AS one FROM "artists" WHERE ("artists"."name" = 'TestArtist1' AND "artists"."id" != 1) LIMIT 1 sql (0.7ms) INSERT INTO "tracks" ("created_at","lyrics","name","updated_at") VALUES ($1,$2,$3,$4) RETURNING "id" [["created_at",Thu,13 Jun 2013 22:20:14 UTC +00:00],["lyrics","test_lyrics"],["name","test_name"],["updated_at",13 Jun 2013 22:20:14 UTC +00:00]] # # Y U NO have artist_tracks.artistic_role_id? # sql (0.7ms) INSERT INTO "artist_tracks" ("artist_id","created_at","track_id",$4) RETURNING "id" [["artist_id",1],["created_at",["track_id",12],13 Jun 2013 22:20:14 UTC +00:00]] (1.0ms) COMMIT
根据Rails Guide for Active Record Associations (4.3.3.1 where),我相信我对范围和期望的使用是有效的:
If you use a hash-style where option,then record creation via this
association will be automatically scoped using the hash.
为什么artist_tracks.artistic_role_id属性丢失了?如果我的期望是错误的,我想了解为什么以及如何实施替代解决方案.
我也把它列为an issue on the Rails repo.任何见解都表示赞赏!谢谢
解决方法
我相信发生的事情是这里实际创建的关联模型是连接模型,artist_tracks,而不是与其实际条件的关联.您可以通过声明与条件的备用连接关联,然后通过它附加owning_artists来解决此问题.像这样:
class Track < ActiveRecord::Base has_many :artist_tracks has_many :owning_artist_tracks,-> { where(:artistic_role_id => 1) },:class_name => "ArtistTrack" has_many :owning_artists,:through => :owning_artist_tracks,:source => :artist end