Stored Procedures and Rails - Part 1

3 12 2007


There is no documentation in Rails about how to use stored procedures or atleast it is difficult to find where to look at. And according to DHH stored procedures is not the Rails Way to do things. DHH mentioned in his post

I want a single layer of cleverness: My domain model. Object-orientation is all about encapsulating clever. Letting it sieve half ways through to the database is a terrible violation of those fine intentions. And I want no part of it.

I somewhat agree to what DHH has to say. And that’s all fine but what if we don’t have any other option apart from using stored procedure and our stored procedure has some complex logic which we don’t want to put in our Ruby code then here is a little hack to it

ActiveRecord::Base.connection.execute("execute procedure_name")

But the above line will not return anything it will only execute your procedure, considering everything went OK.

Moreover, it’s not DRY if everytime you have to write that line of code just to call a procedure.

Here is a better way to do it:

1) Create a class and let’s call it

Class CallStoredProcedures
  your methods here .......
end

2) Create a class method within it

def self.fetch_db_records(proc_name_with_parameters)
  ActiveRecord::Base.connection.execute(proc_name_with_parameters)
end

Then simply call it as

CallStoredProcedures.fetch_db_records("exec procedure_name 'args1', 'args2', 'and so on' ")

Now you might say, that this will only execute a procedure (as I mentioned above) what if I want to return records or values from stored procedures. Then I will prefer class methods and this is how I would do it,

class CallStoredProcedures < ActiveRecord::Base

  def self.fetch_db_records(proc_name_with_parameters)
    connection.select_all(proc_name_with_parameters)
  end

  def self.insert_update_delete_calculate(proc_name_with_parameters)
    connection.execute(proc_name_with_parameters)
  end

  def self.fetch_val_from_sp(proc_name_with_parameters)
    connection.select_value(proc_name_with_parameters)
  end

end

And then simply call it like

CallStoredProcedures.method_name("exec procedure_name 'args1', 'args2', 'and so on' ")

Sweet…

If you know a better way to do it then I would love to know your views.

Stored Procedures and Rails - Part 2


Sign up and be a part of SPhred.com and don’t forget to invite your friends ;o)


Actions

Information

One response to “Stored Procedures and Rails - Part 1”

26 03 2008
Nicholaslm (18:07:11) :

favorited this one, brother

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>