Forum: Ruby on Rails belongs_to validating presence of foreign key

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.
Aaf8b976fe83ca8483c96096c8069571?d=identicon&s=25 Zach Moazeni (Guest)
on 2007-04-27 05:49
(Received via mailing list)
I've recently read
http://blog.teksol.info/articles/2006/03/08/do-not...
and I seem to be experiencing conflicting behavior with Rails 1.2.3

Parent Table:
id Integer
name String

Child Table:
id Integer
name String
parent_id Integer

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  validates_presence_of :parent_id
end

So from reading the link above, as well as the warning on
http://api.rubyonrails.com/classes/ActiveRecord/Va...
I figured this would work.

parent = Parent.new(:name => "Dad")
child = parent.children.build(:name => "Son")
parent.save!

However I consistently get "ActiveRecord::RecordInvalid: Validation
failed: Children is invalid"

This behavior is exhibited with both "validates_presence_of :parent"
and ":parent_id"

However, if I remove the "validates_presence_of :parent_id" both
elements are saved and the Child has been saved with the parent id
appropriately.

Am I mis-reading something, or did this work in previous versions?

Running on Intel Mac, against both SQLite3 and MySQL.

-Zach
This topic is locked and can not be replied to.