Last Updated: February 25, 2016
·
7.92K
· yannick

Stored Procedures and ActiveRecord

There is no easy way to execute a stored procedure. For that I made a small service on top of ActiveRecord that returns OpenStruct

class StoredProcedureService

  def self.instance
    @instance ||= StoredProcedureService.new
  end

  def execute(name, *args)
    results = []
    begin
      connection.execute("CALL #{name}(#{args.join(',')})").each(as: :hash, symbolize_keys: true) do |row|
        results << OpenStruct.new(row)
      end
    ensure
      connection.close
    end
    results
  end

  def connection
    ActiveRecord::Base.connection
  end
end

Easiest to see it on a gist! https://gist.github.com/3714101

2 Responses
Add your response

Good

over 1 year ago ·

@ohmaneel Thanks

over 1 year ago ·