Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

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

#6342

Given the following models,


class Department < ActiveRecord::Base
  
  has_many :employees
  
end

class Employee < ActiveRecord::Base

  belongs_to :department

end

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


  dept = Department.first

  dept.employees.exists?(nil)

  ...

  => 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.

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

State: invalid
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Franco Catena
    Franco Catena

    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?"

    January 27th, 2011 @ 03:08 PM

  2. Rohit Arondekar
    Rohit Arondekar
    • 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 — https://github.com/rails/rails/blob/master/activerecord/lib/active_... 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.

    January 29th, 2011 @ 01:24 PM