# Best method to save-through to many-to-many

**URL:** <https://www.ruby-forum.com/t/best-method-to-save-through-to-many-to-many/118120>\
**Category:** Rails\
**Created:** [October 24, 2007, 1:37am UTC](https://www.ruby-forum.com/t/best-method-to-save-through-to-many-to-many/118120 "2007-10-24T01:37:51Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![davis](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e19adc/32.png) [@davis](https://www.ruby-forum.com/u/davis)\
**Post date:** [October 24, 2007, 1:37am UTC](https://www.ruby-forum.com/t/best-method-to-save-through-to-many-to-many/118120/1 "2007-10-24T01:37:51Z")

</div>

Hi, I’m a noobie, and this is a simple question. If it has already  
been answered a thousand times prior, please just tell me the link 🙂

A book can have many authors…an author can write many books:

I have a simple model Books:

create table books (  
id int not null auto\_increment,  
isbn varchar(25) not null,  
\<etc…other columns here\>  
primary key (id)  
);

class Book \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :authors

\<etc…\>

A simple model Authors:

create table authors (  
id int not null auto\_increment,  
first\_name varchar(25) not null,  
last\_name varchar(25) not null,  
primary key (id)  
);

A simple join table for many-to-many:

create table authors\_books (  
book\_id int not null,  
author\_id int not null,  
constraint fk\_ab\_book foreign key (book\_id) references books(id),  
constraint fk\_ab\_author foreign key (author\_id) references  
authors(id)  
) ;

class Author \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :books

\<etc…\>

Here’s my question:

When I create a new book, I need to compile the list of authors and  
save them so they’ll be linked with the book via the authors\_books  
table. If the author already exists, I want to re-use that author in  
the db, and not create a new author.

Pseudo-code like this (not ruby):

book = Book.new( …all book params here)

foreach author a:  
if author already exists in db  
authors.add(a)  
else  
author = Author.new(first\_name, last\_name)  
authors.add(author)  
end

book.authors = authors

book.save

* * *

I think this must be a pattern that the rails framework has tools for,  
but I’m just not that familiar. Is there a recommended way to go? I  
can certainly code it and make it work, but wondering if there are  
ActiveRecord tools that make this easy?

Regards,  
Davis
