Hey railers!
I''ve got two models that have a one-to-many relationship, should the
model
enforce the foreign key relationship?
Should the example below cause ''p.save'' to fail, as the
user_id field hasn''t
been set? Or should I avoid creating pictures directly and create them
through a User instance? Or should I beat it/myself with a hammer until it
doesn''t matter? ;-)
Thanks
-- 8< ---- 8< ---- 8< ---- 8< ---- 8< ---- 8< --
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL auto_increment,
..
)
CREATE TABLE `pictures` (
`id` int(11) unsigned NOT NULL auto_increment,
`user_id` int(11) unsigned default NULL,
..
)
class User < ActiveRecord::Base
has_many :pictures
end
class Picture < ActiveRecord::Base
belongs_to :user
end
code:
p = Picture.new
p.save # BOOM?
> I''ve got two models that have a one-to-many relationship, should the model > enforce the foreign key relationship?No, the DBMS should, but you''re using MySQL with MyISAM tables, which doesn''t enforce FK rules.> Should the example below cause ''p.save'' to fail, as the user_id field hasn''t > been set? Or should I avoid creating pictures directly and create them > through a User instance? Or should I beat it/myself with a hammer until it > doesn''t matter? ;-)It should save with a NULL foreign key, which is valid. If you specify the FK as NOT NULL it should fail. -- Phillip Hutchings http://www.sitharus.com/ sitharus-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org / sitharus-QrR4M9swfipWk0Htik3J/w@public.gmane.org
>> I''ve got two models that have a one-to-many relationship, should themodel>> enforce the foreign key relationship?> No, the DBMS should, but you''re using MySQL with MyISAM tables, which > doesn''t enforce FK rules.Ah, I was just wondering if maybe I''d missed something in my model definition - that makes perfect sense :-) Thanks for your quick reply, Paul