Validates :presence of belongs_to association incorrectly succeeds #2749

jaylevitt opened this Issue Aug 30, 2011 · 2 comments


None yet
2 participants

jaylevitt commented Aug 30, 2011

As the guides say, the proper way to validate the presence of an object associated with belongs_to is to validate the foreign key, not the object itself.

However, I'd expect that validating the incorrectly-declared object should fail, e.g. given

class User
    belongs_to :group
    validates :group, :presence => true

I would expect

u =
u.valid? #=> false

Instead, it silently succeeds:

u.valid? #=> true #=> true #=> NilClass

I thought that maybe was always some type of ActiveRecord::Association object and thus would always succeed, but no, it's a nil. So I'm not sure why :presence is succeeding, but it should fail if I'm doing it wrong.


andmej commented Aug 31, 2011

I can't reproduce this against master. This is my model:

class Client < ActiveRecord::Base
  belongs_to :group
  validates :group, :presence => true

And I get:

$ rails c
Loading development environment (Rails 3.2.0.beta)
ruby-1.9.2-p290 :001 > c =
c => #<Client id: nil, first_name: nil, orders_count: nil, locked: true, created_at: nil, updated_at: nil, group_id: nil> 
ruby-1.9.2-p290 :002 > c.valid?
 => false 
ruby-1.9.2-p290 :003 > c.errors.full_messages
 => ["Group can't be blank"]

What Rails version are you using?


jaylevitt commented Aug 31, 2011

I can't duplicate it either now (3.0.9). Must have been a reload! problem. Or maybe it only happens on August 30 - I'll check again next year.

@jaylevitt jaylevitt closed this Aug 31, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment