Get connected
find your true connection with railsIn Rails, the database connection hides behind an adapter. This adapter allows you to execute queries, but you cannot bind variables in a safe manner where the database driver does the escaping for you. Not something you want in a web-application where SQL injection should be on the top of your list of concerns.
Here's a little snippet of code to put in lib/adapter_connection.rb of your RAILS_ROOT to be able to obtain the true connection and start binding and escaping.
# this will grant access to the true database connection which is hidden
# in the current ConnectionAdapter.
#
module AdapterConnection
def get_true_connection
adapter = ActiveRecord::Base.connection
# when we cannot get the TRUE connection yet, make it so
unless adapter.respond_to?(:get_connection)
klass = adapter.class
klass.class_eval do
def get_connection
@connection
end
end
end
# return the TRUE connection
adapter.get_connection
end
end
Be aware that the way binding occurs differs for different database drivers so you should be pretty sure this is the only way, since it isn't very portable!
Now in your model you would want to add the following lines of code:
class MyModel << ActiveRecord::Base
include AdapterConnection
def my_tailored_query
conn = get_true_connection
# ...
end
end
Comments
Want to comment?

But I disagree; in the normal rails operation there is absolutely no need for by-passing the current adapter. But when you are, like I was last week, building a rails based SOAP service on top of an existing and fully functional Oracle system where there is no place for Rails specific tables and there are views and trigger tables to fulfill your needs it is nonsense to force Rails to use ActiveRecord and models and it speeds up development to utilize custom queries with the true connection.
DRY and KISS is also leaving the framework when it is required.