Is it common practice that stored procedures/sql functions are not preferred to use?
True. Building queries with Active Record allow you to manage them all in your application code.
What are pros and cons of using stored procedures?
Pros: you can hide complex query logic from your application code.
Cons: you have to create and execute a migration if you want to rewrite a procedure.
See this example on hiding logic in a database view, also applicable to procedures.
Pros Example:
You need to select all hotels with rooms available between start_time
and end_time
. Every hotel has total_rooms (integer attribute), hotel_times (entity that define operating hours for a hotel) and some bookings (entity that define a user that booked a room in a hotel). Some hotels are big and offer daily bookings. Other hotels are small and offer hourly bookings. You ask the user when he wants to book, which can be either a date or a date-with-time.
This involves some joins and sub-queries and would create a big ugly piece of Active Record code. Instead, you can write a procedure and call it like this:
Hotel.find_by_sql ['SELECT * FROM hotels_available_between(?, ?)', start_time, end_time]
Wrap it in a scope and get more ruby-ish:
class Hotel < ActiveRecord::Base
scope :available_between, -> start_time, end_time do
find_by_sql ['SELECT * FROM hotels_available_between(?, ?)', start_time, end_time]
end
end
Hotel.available_between start_time, end_time