DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Daniel has posted 5 posts at DZone. View Full User Profile

ActiveRecord::Base.foreach (for Oracle Users)

11.02.2010
| 4993 views |
  • submit to reddit
        # Iterate over one record at a time using ActiveRecord, instead of being slurpy.

def self.foreach(conditions = nil, &block)
  conn = connection.raw_connection

  sql = "select * from #{table_name}"
  sql += " where #{conditions}" if conditions

  begin
    raw_cursor  = conn.exec(sql)

    while rec = raw_cursor.fetch_hash
      object = self.new

      # To get around protected attributes we must assign all attributes
      # individually, instead of passing a single hash to self.new.
      rec.each{ |key, value|
        cname = key.downcase
        object.send("#{cname}=", value)
      }

      yield object
    end
  ensure
    raw_cursor.close if raw_cursor
  end
end