Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Validates :presence of belongs_to association incorrectly succeeds #2749

Closed
jaylevitt opened this Issue · 2 comments

2 participants

@jaylevitt

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
end

I would expect

u = User.new
u.valid? #=> false

Instead, it silently succeeds:

u.valid? #=> true
u.group.blank? #=> true
u.group.class #=> NilClass

I thought that maybe u.group 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

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

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

And I get:

$ rails c
Loading development environment (Rails 3.2.0.beta)
ruby-1.9.2-p290 :001 > c = Client.new
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

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.