Ruby ActiveRecord有很多功能:通过不';不要通过计算机赋值

Ruby ActiveRecord有很多功能:通过不';不要通过计算机赋值,ruby,activerecord,sinatra,sinatra-activerecord,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 ActiveRecord就是这样工作的吗?我该怎么解决这个问题呢?好的,我这里有问题。在调用artist.genres之前,您需要保存您的歌曲记

我正在与一个歌曲、流派和艺术家模型合作。这些类如下所示:

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

ActiveRecord就是这样工作的吗?我该怎么解决这个问题呢?

好的,我这里有问题。在调用
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>]>
>artist=artist.new
=> #
>艺术家拯救
=>正确
>新的
=> #
>歌手
=> #
>genre=genre.new
=> # 
>歌曲类型
#在保存歌曲之前`
>艺术流派
=> # 
>宋。保存
=>正确
#保存“歌曲”后`
>艺术流派
=> #

如果有帮助,请告诉我。

song.genres中
流派是什么对不起,
#
问题是我不能做
artist.genres我没有做。你不必这么做。你可以做
song.genres
artist.genres
仍然是空的:(你正在运行的确切语句集是什么?从一开始。
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
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
=> []
> 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>]>