This project is archived and is in readonly mode.

#6342 ✓invalid
Cathal O' Riordan

ActiveRecord::Base#exists? returns true when called with nil

Reported by Cathal O' Riordan | January 27th, 2011 @ 12:54 PM

Given the following models,

class Department < ActiveRecord::Base
  has_many :employees

class Employee < ActiveRecord::Base

  belongs_to :department


when determining if an employee belongs to a department using exists?, the following call will return true,

  dept = Department.first



  => true

And according to the documentation,

Returns true if a record exists in the table that matches the id or conditions given, or false otherwise.

I'd assume in the example above, false should be returned if nil is passed.

tested this against Rails v3.0.3 and ruby 1.9.2.

Comments and changes to this ticket

  • Franco Catena

    Franco Catena January 27th, 2011 @ 03:08 PM

    I think that in this case ActiveRecord interpret this question like

    dept.employees.count > 0

    So in a way the question "exists?" is translates to "at least one (without conditions) exists?"

    The behaviour you whant can be achieved with

    dept.employees.exists?(:id => nil)

    And in this case the question "exists?" is translates to "at least one (without id) exists?"

  • Rohit Arondekar

    Rohit Arondekar January 29th, 2011 @ 01:24 PM

    • State changed from “new” to “invalid”
    • Importance changed from “” to “Low”

    I think Franco is right here. In fact the default argument for id is nil hence it works exactly as Franco has explained. I'm closing the ticket but if you still feel there is a discrepancy leave a comment and I'll reopen.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

Referenced by