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.
It’s always good to do validates_presence_of :user_id or else it would freak out if both the objects are new 🙂 Just a minor note..
Thank you for this! I’ve been wondering how to validate my associations and the answer was so obvious.