validating Rails association

Should ActiveRecord add validations based on associations defined in the models?


class User < ActiveRecord::Base 
  has_many :posts 
end 

class Post < ActiveRecord::Base 
  belongs_to :user 
end 

If i create an instance of a post with a user_id that does not exist in the Users table, I wish ActiveRecord threw up a validation error on saving this instance of post.
It does not do so by default, so here are the validations that I add to my models to implement this.


class User < ActiveRecord::Base 
  has_many :posts 
end 


class Post < ActiveRecord::Base 
  belongs_to :user 
  validates_associated :user 
  validates_presence_of :user 
end 


Now if I try and save a post without a user_id or with a user_id that is not found in the Users table, an exception is thrown.

Till now I always use to create foreign keys in my database, as a safety net. So that the db throws an error if my data is not consistent.
After adding these validations, I hope not to have foreign keys in the database anymore.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

thirty eight − = thirty