2012-04-18 42 views
0

我目前有一个名为Album的模型,其中has_many :songs。我希望用户能够将歌曲从一个专辑移到另一个专辑。在Rails的控制台瞎搞,我发现更改模型对象的ID

song.album_id=2 
song.save 

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

回答

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 
+0

起飞之前,务必确保这张专辑其实这种方式存在请注意,'update_attribute'跳过任何验证,检查,无论如何,它都会直接替换数据库中的属性 – 2012-04-18 06:43:25

+0

@AndreiS是的,我已经更新了答案。谢谢你的建议:) – 2012-04-18 06:49:10

1

这里没有什么不寻常的:

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

两个做他们的工作。

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 

指定曲目将其