Foreign Keys and Entering Data


I’m new to Rails and Database Programming in general. I’m trying to
create a site where there is a list of books and the authors. Right
now I’ve got a two tables in my database. One contains information
about books, and the other contains the authors. There is a foreign
key(author_id) in the books table linking to the id row in the author
table. To enter the information there is a form(I haven’t made it
yet) that asks for the book title, the published date, and the
author’s first, middle and last name.

Does Rails check for redundancy automatically as far as data is
concerned for foreign keys? Let’s say my first entry is a book by
Stephen King. Now let’s say I want to enter another book by Stephen
King. Do I write the code checking to see if the author already
exists in the DB and then setting the value of that foreign key, or is
there something in Ruby/Rails that does this for me? If there is some
way that Ruby/Rails does this automatically, what keywords should I be
using to find more information?


The part on “dynamic finders” in the AR::Base docs may be what your
looking for. Look for find_or_create_by and find_or_initialize_by in