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

Ticket #5974 (closed enhancement: incomplete)

Opened 4 years ago

Last modified 3 years ago

Add a find! method to ActiveRecord base that raises RecordNotFound

Reported by: t.lucas@toolmantim.com Assigned to: David
Priority: normal Milestone:
Component: ActiveRecord Version:
Severity: normal Keywords: RecordNotFound find bang!
Cc:

Description

As per the discussion on rails-core.

The following simple implementation works fine, but ideally you want to to add it to the magic finders too.

module ActiveRecord
  class Base
    def find!(*args)
      records = find(args)
      raise RecordNotFound, "Couldn't find #{name} without an ID" if records.blank?
      records
    end
  end
end

This opens up a nice convention for 404 handling.

Change History

(in reply to: ↑ description ) 10/16/06 12:54:19 changed by twodecode

  • keywords set to RecordNotFound find bang!.

In addition some other things should be changed to the find method, specifically concerning the id based finds.

>> Model.find(2).id
=> 2
>> Model.find(234).id
ActiveRecord::RecordNotFound: Couldn't find Model with ID=12342
        from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:955:in `find_one'
        from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:941:in `find_from_ids'
        from /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/base.rb:382:in `find'
        from (irb):2
        from :0
>> Model.find(:first, :conditions => ['id = ?', 234])
=> nil

This isn't what I would call consistent. I find that non-bang! find methods should only raise an error if query itself is wrong. When there is nothing found the non-bang! methods should return [] or nil depending on the request.

the bang! finds then have the simple task of raising RecordNotFound when the find method underneath returns [] or nil.

05/27/07 05:53:55 changed by danger

+1 for this change. I agree that the finders are inconsistent and it would be great to have errors raised for find*! and the non-bang finders simply return nil or [].

anyone want to create a patch with tests?

05/29/07 07:19:12 changed by brynary

  • status changed from new to closed.
  • resolution set to incomplete.

Closing because there is no patch.