# Foreign Keys and Entering Data

**URL:** <https://www.ruby-forum.com/t/foreign-keys-and-entering-data/106545>\
**Category:** Rails\
**Created:** [June 11, 2007, 8:39pm UTC](https://www.ruby-forum.com/t/foreign-keys-and-entering-data/106545 "2007-06-11T20:39:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![oozy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6bbea6/32.png) [@oozy](https://www.ruby-forum.com/u/oozy)\
**Post date:** [June 11, 2007, 8:39pm UTC](https://www.ruby-forum.com/t/foreign-keys-and-entering-data/106545/1 "2007-06-11T20:39:10Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![oozy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6bbea6/32.png) [@oozy](https://www.ruby-forum.com/u/oozy)\
**Post date:** [June 12, 2007, 7:32pm UTC](https://www.ruby-forum.com/t/foreign-keys-and-entering-data/106545/2 "2007-06-12T19:32:42Z")

</div>

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/Base.html

-John

---

<div class="post-metadata">

**Author:** ![oozy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/6bbea6/32.png) [@oozy](https://www.ruby-forum.com/u/oozy)\
**Post date:** [July 2, 2007, 2:21am UTC](https://www.ruby-forum.com/t/foreign-keys-and-entering-data/106545/3 "2007-07-02T02:21:34Z")

</div>

Thanks!
