Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

ActiveRecord: For NEW record 'has_and_belongs_to_many' 'exists?' return true #6199

Sega100500 opened this Issue May 8, 2012 · 2 comments


None yet
2 participants


I have a models:

class User < ActiveRecord::Base
  has_many :users_groups, :class_name => 'UsersGroups'
  has_and_belongs_to_many :groups, :join_table => :users_groups


class Group < ActiveRecord::Base
  has_many :users_groups, :class_name => 'UsersGroups'
  has_and_belongs_to_many :users, :join_table => :users_groups

If I request belonging to group for EXISTING @user by 'group.users.exists?(@user)' then it works correctly, perfectly.

When I reqest belonging to group for NEW USER by 'group.users.exists?(@user)' - it ALWAYS return TRUE.
But more logical will assume that the nonexistent user still isn't present in any group.


pixeltrix commented May 8, 2012

Actually it's nothing to do with associations, e.g:

class User < ActiveRecord::Base; end
>> User.exists?(User.new)
=> true

@jonleighton it looks as though these two lines need swapping - want me to handle it?

Yes, need swapping two lines.

May be correct:

def exists?(id = false)

  id = id.id if ActiveRecord::Model === id

  return false if id.nil?  # id.id == nil for new record


@pixeltrix pixeltrix was assigned May 10, 2012

@pixeltrix pixeltrix closed this in fa21b73 May 10, 2012

@arunagw arunagw pushed a commit to arunagw/rails that referenced this issue May 11, 2012

@pixeltrix pixeltrix Return false for exists? with new records - fixes #6199.
(cherry picked from commit fa21b73)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment