I have a model with a foreign key. Even though there’s a database constraint preventing a duplicate user_id from entering SomeClass‘s table, I’m repeating (pre-empting, really) that validation in the model so that it’s handled more gracefully. So my model looks something like this:
class SomeClass < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
validates_uniqueness_of :user_id
...
end
It took me a while to realize this is how it needs to be done. It seems to me that ActiveRecord should expect you to use either user or user_id consistently on both presence and uniqueness validation. That would make:
validates :user, :presence => true, :uniqueness => true
or:
validates :user_id, :presence => true, :uniqueness => true
possible, which is optimal for code maintainability since it groups all user constraints together. So why instead is it inconsistent?
I believe the reason lies in difference between
user_idanduser.Presence of
usermakes sure not only existence ofuser_id, but also presence of the actual user.As checking uniqueness of user_id and user, AFAIK they may have the same effect, checking of user_id is enough it make sure it is unique.