Everyone seems to discourage the use of raw SQL in Ruby applications and while ActiveRecord seems a good solution for general purpose CRUD operations, we have a strong expertise in SQL and we want to use it as much as possible. Here are the bits we have collected so far on the subject. We are new to Ruby/Rails so these might be obvious for some of you. We primarily write this for ourselves.
We are perfectly aware of the “limitations”. We love PostgreSQL and have no intention of being RDBMS-agnostic. At all.
find_by_sql the way we want it
We want named parameters because, despite the overhead, it’s the cleanest way to pass parameters (we don’t have to preserve a strict order which can lead to problems when enhancing the query, counting the “?”, etc). Also, when we use the same parameter several times in the same query, we don’t have to repeat it.
class ClientsController < ApplicationController
def index
@clients = Client.find_by_sql(
<<-SQL
SELECT idclient,name,email,contacts
FROM clients
ORDER BY nom
SQL
)
end
def show
@client = Client.find_by_sql(["
SELECT idclient,name,email,contacts
FROM clients
WHERE idclient = :idclient",
{ :idclient => params[:id] }
])[0]
end
For the show
method, we have to grab the first element in the array (thus the [0]
at the end.