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

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 :slight_smile:

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