# Find\_or\_initialize\_by and Nested Resources

**URL:** <https://www.ruby-forum.com/t/find-or-initialize-by-and-nested-resources/73130>\
**Category:** Rails\
**Created:** [October 21, 2006, 8:42pm UTC](https://www.ruby-forum.com/t/find-or-initialize-by-and-nested-resources/73130 "2006-10-21T20:42:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Shane\_V](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/e68b1a/32.png) [@Shane\_V](https://www.ruby-forum.com/u/Shane_V)\
**Post date:** [October 21, 2006, 8:42pm UTC](https://www.ruby-forum.com/t/find-or-initialize-by-and-nested-resources/73130/1 "2006-10-21T20:42:33Z")

</div>

Hey guys,

Lets say I have the following nested resources:

map.resource artists do |artists|  
map.resource songs  
end

To create a new song, the url would be:

/artists/:artist\_id/songs/:song\_id

However, lets say that an artist doesn’t exist yet. I only want to  
create an artist if a new song by the artist is successfully saved. I  
am retrieving the artist using something like:

@artist = find\_or\_intialize\_by\_country\_id(@country)

Since the artist doesn’t exist yet, there will be no ‘id’ attribute  
yet. However, I have to pass in an id to the url which creates the  
song, ie:

new\_song\_path(@artist)

This will obviously fail since @artist.id is nil. I can use  
find\_or\_create\_by instead, but then if the user cancels creating a  
song, I will be left with an extra row in the artist table that I  
don’t need.

Any ideas?

Shane V.  
[http://shanesbrain.net](http://shanesbrain.net)
