Reputation: 71
I have this code in my model:
validates :user, presence: true, uniqueness: {scope: :project}
The individidual validators, presence and uniqueness, each work fine if the other one isn't there. But if they are both present as above, the presense validator stops working. When I try to save an object that has a nil user, instead of getting an normal save error, i get an exception:
NoMethodError: undefined method 'attributes' for nil:NilClass from /usr/local/lib/ruby/gems/2.0.0/gems/activerecord-4.0.2/lib/active_record/validations/uniqueness.rb:56:in `build_relation'
Is this a bug in ActiveRecord or am I doing something wrong?
Upvotes: 4
Views: 8571
Reputation: 2923
Found a solution (https://github.com/thoughtbot/shoulda-matchers/issues/459), but I don't think this is the best/right way. Just add allow_nil: true
.
Then it should be like:
validates :user, presence: true, uniqueness: {scope: :project}, allow_nil: true
Upvotes: 4