<p>I'm sure this is a relatively simple question, and there must be a good sensible rails way of doing it, but I'm not sure what it is.</p>

<p>Basically I'm adding books to a database, and I want to store the Author in a separate table. So I have a table called authors which is referenced by the table books.</p>

<p>I want to create a rails form for adding a book, and I'd like it to be just a simple form for Author, Title, Publisher etc, and if it finds the author already in the authors table then it should just reference that record, and if it isn't in the authors table then it should add a new record and reference it.</p>

<p>I'm sure there's an easy way of doing this in rails - but I can't seem to find it.</p>

<p>Cheers,</p>

<p>Robin</p>

Assuming that your form passes an author_name and a book hash with the book attributes, you could do the following in your controller:
```
```
@author = Author.find_or_create_by_name(params[:author_name])
@book = Book.new(params[:book])
@book.author = @author
@book.save
```
```
This will find an author by that name, or create one, then assign that author to the book that's created.
Note: This also assumes that authors can be uniquely identified by their name, and this usually isn't the case.  There could be multiple guys namned "Steven King" out there, for instance, and only one of them wrote
The Shining