通过具有范围的关联保存时丢失属性(Rails 4.0.0)

时间:2013-06-13 23:10:51

标签: ruby-on-rails ruby activerecord associations ruby-on-rails-4

代码(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", Thu, 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", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["artist_id", 1], ["created_at", Thu, 13 Jun 2013 22:20:14 UTC +00:00], ["track_id", 12], ["updated_at", Thu, 13 Jun 2013 22:20:14 UTC +00:00]]
   (1.0ms)  COMMIT

根据Rails Guide for Active Record Associations (4.3.3.1 where),我相信我对范围和期望的使用是有效的:

  

如果您使用hash-style where选项,则通过此记录创建   关联将使用哈希自动确定范围。

为什么artist_tracks.artistic_role_id属性丢失了?如果我的期望是错误的,我想了解为什么以及如何实施替代解决方案。

我还将其列为an issue on the Rails repo。任何见解都表示赞赏!谢谢

1 个答案:

答案 0 :(得分:0)

我相信发生的事情是,这里实际创建的关联模型是连接模型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