Forum: Ruby on Rails Foreign Keys and Entering Data

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
oozy (Guest)
on 2007-06-11 22:39
(Received via mailing list)
Hi,

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?

Thanks.
jparker (Guest)
on 2007-06-12 21:32
(Received via mailing list)
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
particular:

<URL:http://api.rubyonrails.org/classes/ActiveRecord/Ba...

-John
oozy (Guest)
on 2007-07-02 04:21
(Received via mailing list)
Thanks!
This topic is locked and can not be replied to.