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 exists? won't work with keyless tables

#615

exists? needs a primary key to work. So it won't work with tables without a primary key.

  1. File activerecord/lib/active_record/base.rb, line 601

601: def exists?(id_or_conditions)

602: connection.select_all(

603: construct_finder_sql(

604: :select => "#{quoted_table_name}.#{primary_key}",

605: :conditions => expand_id_conditions(id_or_conditions),

606: :limit => 1

607: ),

608: "#{name} Exists"

609: ).size > 0

610: end

Reported by flip · July 13th, 2008 @ 11:46 PM

State: wontfix
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Tom Ward
    Tom Ward

    Can you provide a failing test case? The solution is pretty simple (select 1 rather than select primary_key), but in what circumstance would you actually have an ActiveRecord class without a primary key?

    July 26th, 2008 @ 10:55 AM

  2. Pratik
    Pratik
    • State changed from new to wontfix

    I wonder what actually works when you don't have a PK. In any case, you should just write a plugin overriding exists?

    July 26th, 2008 @ 03:06 PM

  3. fearless_fool
    fearless_fool
    • Importance changed from to

    Is there a good explanation for the wontfix status? Specifically, it is surprising that AR.exists?() fails on PK-less tables, given that AR.find() works just fine.

    > UserRole.find(:first, :conditions => {:user_id => 4, :role_id => 2}) => #

    Of course you can emulate AR.exists?() as:

    > !!UserRole.find(:first, :conditions => {:user_id => 4, :role_id => 2}) => true

    • ff

    P.S.:

    create_table "user_roles", :id => false, :force => true do |t|

    t.integer "user_id"
    t.integer "role_id"
    

    end

    and

    $ rake about About your application's environment
    Ruby version 1.9.2 (x86_64-darwin10.4.0)
    RubyGems version 1.3.7
    Rack version 1.2
    Rails version 3.0.0
    Active Record version 3.0.0
    Action Pack version 3.0.0
    Active Resource version 3.0.0
    Action Mailer version 3.0.0
    Active Support version 3.0.0
    Application root /Users/ff/Developer
    Environment development

    October 26th, 2010 @ 07:06 PM

  4. fearless_fool
    fearless_fool
    • Tag changed from 2.1, activerecord, bug to 3.0, activerecord, bug

    Doh - once again with formatting...

      > UserRole.find(:first, :conditions => {:user_id => 4, :role_id => 2})
      => #<UserRole user_id: 4, role_id: 2>
    

    Of course you can emulate AR.exists?() as:

      > !!UserRole.find(:first, :conditions => {:user_id => 4, :role_id => 2})
      => true
    

    P.S.: Since this was originally a 2.1 ticket, please let me know if I should open a new ticket altogether for 3.0...

    October 26th, 2010 @ 07:11 PM