ActiveRecord has_many :through 不通过赋值

ActiveRecord has_many :through doesn't assign value through

我正在处理歌曲、流派和艺术家模型。 类 如下所示:

class Genre < ActiveRecord::Base
    has_many :song_genres
    has_many :songs, through: :song_genres
    has_many :artists, through: :songs
end

class Artist < ActiveRecord::Base
    has_many :songs
    has_many :genres, through: :songs
end

class Song < ActiveRecord::Base
    belongs_to :artist
    has_many :song_genres
    has_many :genres, through: :song_genres
end

class SongGenre < ActiveRecord::Base
    belongs_to :song
    belongs_to :genre
end

我遇到的问题是,当我将一首歌曲(已经分配了一个流派)分配给一位艺术家时,该流派无法通过 artist.genres 用于艺术家实例。下面是我的意思的一个例子:

song.genres << genre
=> [#<Genre:0x00007faf02b914b0 id: 2, name: "Pop">]
[10] pry(main)> song.genres
=> [#<Genre:0x00007faf02b914b0 id: 2, name: "Pop">]
[11] pry(main)> song.artist = artist
=> #<Artist:0x00007faf044cb048 id: 2, name: "James Blunt">
[12] pry(main)> artist.genres
=> []

ActiveRecord 是这样工作的吗?我该如何解决这个问题?

好的,我在这里遇到了问题。在调用 artist.genres 之前,您需要 save 您的 song 记录。除非您保存,否则不会将流派分配给相关艺术家。

> artist = Artist.new
 => #<Artist id: nil>

> artist.save
 => true 

> song = Song.new
 => #<Song id: nil, artist_id: nil>
> song.artist = artist
 => #<Artist id: 1>

> genre = Genre.new
 => #<Genre id: nil> 

> song.genres << genre
 => #<ActiveRecord::Associations::CollectionProxy [#<Genre id: nil>]> 

# Before saving `song`
> artist.genres
  => #<ActiveRecord::Associations::CollectionProxy []> 

> song.save
 => true 

# After saving `song`
> artist.genres
 => #<ActiveRecord::Associations::CollectionProxy [#<Genre id: 1>]>

如果有帮助请告诉我。