Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 4655

Show
Ignore:
Timestamp:
08/03/06 22:06:33 (2 years ago)
Author:
bitsweat
Message:

The exists? class method should treat a string argument as an id rather than as conditions. Closes #5698.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activerecord/CHANGELOG

    r4652 r4655  
    11*SVN* 
     2 
     3* The exists? class method should treat a string argument as an id rather than as conditions.  #5698 [jeremy@planetargon.com] 
    24 
    35* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com] 
  • trunk/activerecord/lib/active_record/base.rb

    r4651 r4655  
    427427      # Example: 
    428428      #   Person.exists?(5) 
     429      #   Person.exists?('5') 
    429430      #   Person.exists?(:name => "David") 
    430       def exists?(conditions) 
    431         conditions = ["#{primary_key} = ?", conditions] if conditions.is_a?(Fixnum) 
    432         !find(:first, :conditions => conditions).nil? rescue false 
     431      #   Person.exists?(['name LIKE ?', "%#{query}%"]) 
     432      def exists?(id_or_conditions) 
     433        !find(:first, :conditions => expand_id_conditions(id_or_conditions)).nil? 
     434      rescue ActiveRecord::ActiveRecordError 
     435        false 
    433436      end 
    434437 
     
    12241227          end 
    12251228        end 
     1229 
     1230        # Interpret Array and Hash as conditions and anything else as an id. 
     1231        def expand_id_conditions(id_or_conditions) 
     1232          case id_or_conditions 
     1233            when Array, Hash then id_or_conditions 
     1234            else construct_conditions_from_arguments([primary_key], [id_or_conditions]) 
     1235          end 
     1236        end 
     1237 
    12261238 
    12271239        # Defines an "attribute" method (like #inheritance_column or 
  • trunk/activerecord/test/finder_test.rb

    r4651 r4655  
    2121   
    2222  def test_exists 
    23     assert (Topic.exists?(1)) 
    24     assert (Topic.exists?(:author_name => "David")) 
    25     assert (Topic.exists?(:author_name => "Mary", :approved => true)) 
    26     assert (Topic.exists?(["parent_id = ?", 1])) 
    27     assert !(Topic.exists?(45)) 
    28     assert !(Topic.exists?("foo")) 
    29     assert !(Topic.exists?([1,2])) 
     23    assert Topic.exists?(1) 
     24    assert Topic.exists?("1") 
     25    assert Topic.exists?(:author_name => "David") 
     26    assert Topic.exists?(:author_name => "Mary", :approved => true) 
     27    assert Topic.exists?(["parent_id = ?", 1]) 
     28    assert !Topic.exists?(45) 
     29    assert !Topic.exists?("foo") 
     30    assert_raise(NoMethodError) { Topic.exists?([1,2]) } 
    3031  end 
    3132