0

我目前有一个名为Albumwhich的模型has_many :songs。我希望用户能够将歌曲从一张专辑移动到另一张专辑。在 Rails 控制台中乱搞,我发现

song.album_id=2
song.save

工作正常,但是,我怀疑这是在实际应用程序中应用它的正确方法。有没有合适的方法来做到这一点?

4

3 回答 3

1

这里没有什么不寻常的:

song.album_id=2
# or
song.album = @album

两者都做他们的工作。

于 2012-04-18T06:38:38.040 回答
1

通过拥有这些:

album has_many :songs
song belongs_to :album

你可以这样做:

#find your album, by params[:id] or any other means you wish

album = Album.find(params[:id])

#assign it to the song

song.album = album

这样,您就可以在为其分配歌曲之前确保专辑确实存在

于 2012-04-18T06:41:42.123 回答
1
@album = Album.find_by_id(10)
#This is the album to move song
@song = Song.find_by_id(100)
#This is the song to be moved
@song.album = @album
@song.save
于 2012-04-18T06:41:55.023 回答