Should I validate the presence of a foreign key?

Pretty quick example, imagine we have two classes, a user and a post.
class Post < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
end

This basically just ensures that no post is created without a user id.
However if I do something like this (assuming a User has_many :posts)
user.posts << Post.new({ :subject = “post subject” })
user.save

Then I get an error saying “Posts is invalid.” Take out the
validates_presence_of :user_id and it works fine.

Should I not be validating the presence of foreign keys like this?
What’s the best way to ensure that a fkey is set up - or is there even
any reason to? I have constraints set up in my DB, but I was
wondering if I should/need to make a check in Rails. Am I good to go
as long as I set relations properly, i.e. user.posts << Post.new…
post.user = thisuser, etc, rather than accessing the id directly.

Thanks,
Pat

On 12/1/05, Pat M. [email protected] wrote:

Then I get an error saying “Posts is invalid.” Take out the
validates_presence_of :user_id and it works fine.

Should I not be validating the presence of foreign keys like this?
What’s the best way to ensure that a fkey is set up - or is there even
any reason to? I have constraints set up in my DB, but I was
wondering if I should/need to make a check in Rails. Am I good to go
as long as I set relations properly, i.e. user.posts << Post.new…
post.user = thisuser, etc, rather than accessing the id directly.

Do you get the same negative results when using user.posts.create() or
user.posts.build()? I’m not sure if your example is supposed to work
since I find the API docs a bit ambiguous when it comes to what the
different methods defined by the has_many macro are supposed to do.

Hoping this helps,

  • Rowan

perhaps the problem lies in the definition of your users class. Can you
post the code from this class?

-steven

def User < ActiveRecord::Base
has_many :posts
end

Complex enough? :slight_smile:

Pat