This post explains how to use Ruby Sequel and Active Record depending on the complexity of your SQL queries. A real lifesaver when you work with loads of databases!
When you spend all day looking at selects, inserts, updates, functions, views, and stored procedures, your perception of the world can get a little skewed. After a long day of SQL, I’d find myself in the supermarket thinking
select t.tea from tea_and coffee_section as t
where manufacturer = ‘tetley’ and type = ‘earl_grey’ order by price desc. After a while, I decided to move on and start learning Ruby on Rails. Boom! I discovered ActiveRecord! Wow! No fuss SQL and Ruby code, cool. But this incredible discovery turned sour when dealing with more complex queries. My co-workers and I found a solution to our pains: Ruby Sequel.
Well, it’s partially a matter of taste. It would be unfair to say: “Sequel is the best and ActiveRecord is for SQL ignoramuses” because this is simply not true. Active Record is supposed to be database-agnostic, which is good in some cases. But, realistically, having an application with more than 10 models, we won’t be changing the database engine to anything else. And since we won’t change the database engine, why not use database specific features?
Here are some examples of what we can do with Sequel:
which is translated to:
Additional invoking of
to_hash_groups will not give us a flat array of users, but rather a hash where users are grouped by their group names, and every user model will have
Hooray! We had found a remarkable gem, but how did we migrate to Sequel in an application with more than 30 ActiveRecord models?
We had 2 options:
I don’t have to explain why the first option is bad - every day someone wanted some new major or minor feature.
So we took the second option.
These simple steps made this work:
and in application.rb:
and that's it!
To migrate the application to Sequel, we need to rewrite models in logic groups. Because we have models related to each other (User -> Profile -> Group), we need to migrate all of them before deploying, as we can’t have
User extended from
Sequel::Model related to the
Profile model extended from
ActiveModel. There is, of course, the situation in which one or more models are used across the whole application (User). In this case, we need to define a new model with its own name :
And we’re done!
I hope you found my solution useful! In case you did - would you care to spread the word and retweet this article? Many thanks, I'd really appreciate that!