ActiveRecord has_many:通过不分配值

时间:2017-11-23 12:23:54

标签: ruby activerecord sinatra sinatra-activerecord

我正在使用歌曲,流派和艺术家模型。课程如下所示:

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的工作原理吗?我怎么能绕过这个?

1 个答案:

答案 0 :(得分:2)

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

> 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>]>

如果有帮助,请告诉我。