user1015523
user1015523

Reputation: 332

Changing the ID of a model object

I currently have a model called Album which has_many :songs. I would like a user to be able to move songs from one album to another. Messing around in the Rails console, I have found that

song.album_id=2
song.save

works fine, but, I am having doubts that this is the right way to apply it in a real application. Is there a proper way to do this?

Upvotes: 0

Views: 59

Answers (3)

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

@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

Upvotes: 1

Andrei S
Andrei S

Reputation: 6516

By having these:

album has_many :songs
song belongs_to :album

You could do this:

#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

This way you are making sure the album actually exists before assigning a song to it

Upvotes: 1

jdoe
jdoe

Reputation: 15771

Nothing unusual here:

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

Both do their job.

Upvotes: 1

Related Questions