gpt4 book ai didi

ruby-on-rails - 通过带作用域的关联保存时丢失属性 (Rails 4.0.0)

转载 作者:数据小太阳 更新时间:2023-10-29 07:01:01 25 4
gpt4 key购买 nike

代码(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) ,我相信我对范围和期望的使用是有效的:

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

关于ruby-on-rails - 通过带作用域的关联保存时丢失属性 (Rails 4.0.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17098708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com