1.
foreign keys are used to reference other object types. there is no
way to automagically tell the type of a tent unless you reference the
type table in some way. and this is where foreign key''s come in.
in ror you would go something like:
Tent @tent = Tent.new
@tent.tent_type = TentType.find :first
this will set the tent_type_id on te tent record to the first tent type found.
2.
the exception is cause your trying to reference an object through a
foreign key that does not exist.
ie: in the example abose, trying to save @tent if no tent_type''s exist.
from the looks of it your trying to set the tent_type_id to 0 and
tehre are usually no records with an id of zero, due to most primary
key auto incrementing implementations (if not all) start at 1.
if the tent_type_id field is ''NOT NULL'' then it must reference
a real
tent_type before being saved. if its nullable, you can set this to
null, but NOT zero.
foreign key constraints are to prevent you from saving bogus data that
references void data, leaving you in the future going "ummm ...."
hope this helps.
On 9/26/05, Tobias Jordans
<tobias-zjeZ61prdO8EZ6m2XrtfILNAH6kLmebB@public.gmane.org>
wrote:>
>
> Hi,
>
> I am still working on the ONLamp.com-Tutorial (and on the Agile-Book) and I
> don''t understand those foreign-keys for MySQL.
>
> In the Agile-Book it is described as if they are nessesary for the
> belongs_to-magic. But every time I use them together with those
> model-connections I get an error.
> So I stopped on the Book and started with the ONLamp-Tutorial.
>
> Nothing is said about Foreign-Keys there and my app works fine.
> No I tried adding them afterwards I again I get an exception:
>
> #23000Cannot add or update a child row: a foreign key constraint fails:
> INSERT INTO tents (`name`, `date_update_at`, `desc`, `tent_type_id`, ``)
> VALUES(''Headline'', ''2005-09-26
18:15:00'', ''asdf'', 0, 0)
> script/server:49
>
>
> Question 1:
> Do I need the foreign keys or not? What for?
>
> Question 2:
> Why this exception?
>
>
> Thanks!
>
> ~Tobias
>
> PS: http://wiki.rubyonrails.com/rails/pages/onlampTutorialRevised
>
> --
> Weblog: http://flyingsparks.wwwfiles.de/
>
> _______________________________________________
> Rails mailing list
> Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
--
Zachery Hostens <zacheryph-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>