I have a situation where I have three models, Album, Artists and
class Album < ActiveRecord::Base
class Artist < ActiveRecord::Base
class Song < ActiveRecord::Base
So, an album can have songs that have artists.
The problem is that on the Album create form, the user is allowed to
enter all three values. So, the user may enter an existing album that
has a new song by a new artist. Or they have enter a new album that
has an existing song by an existing artist.
I can't figure out how to manage this create in the controller. So,
far I have:
@artist = Artist.find_or_create_by_name(params[:artists][:name])
@song = Song.find_by_name(params[:songs][:name])
@song = Song.new(:name => params[:songs][:name], :artist_id
flash[:error] = "Couldn't create song"
redirect_to :action => 'new'
@album = Album.new()
@album.item_id = @item.id
@album.song_id = @song.id
flash[:notice] = 'Album was successfully created.'
redirect_to :action => 'show', :id => @album.id
render :action => 'new'
This seems to work, but it feels kludgy and I'm not sure if there is
another, more Rails appropriate way to do it. Any suggestions?