# Nested attributes and deep references

**URL:** <https://www.ruby-forum.com/t/nested-attributes-and-deep-references/177177>\
**Category:** Rails\
**Created:** [October 12, 2009, 9:55pm UTC](https://www.ruby-forum.com/t/nested-attributes-and-deep-references/177177 "2009-10-12T21:55:45Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![bouldr-matt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/85e7bf/32.png) [@bouldr-matt](https://www.ruby-forum.com/u/bouldr-matt)\
**Post date:** [October 12, 2009, 9:55pm UTC](https://www.ruby-forum.com/t/nested-attributes-and-deep-references/177177/1 "2009-10-12T21:55:45Z")

</div>

I’m using nested attributes in a new project, but struggling with one  
issue.

Imagine, for example you have the models User, Book, and Shelf. A user  
has\_many books, and has\_many shelves. A shelf also has\_many books.  
User accepts\_nested\_attributes for books and shelves, and shelves accept  
them for books.

So, if I were to do something like the following pseudo code:

shelf = @user.shelves.find([some conditions])  
book = shelf.books.new([some params])  
book.save()

In this case, the book should be correctly associated with the shelf,  
but it’s not associated with the user. Is there a way to automatically  
have the book be associated with the user that the shelf was associated  
with when the book is created like this? Perhaps through a callback?

Just wondering if there’s a standard way to do this before I go  
re-inventing anything.

Thanks 🙂  
M@
