There's enough for everyone

गते गते पारगते पारसंगते बोधि स्वाहा गते गते पारगते पारसंगते बोधि स्वाहा

ActiveRecord instances from Sequel::Dataset#each

I prefer Sequel::Dataset capabilities to Arel’s Relation for several reasons, not least of which is Sequel’s row_proc. Which lets you bend reality and perhaps time itself when you want the best of both worlds:


1
2
3
4
5
6
7
8
9
10
11
class ActiveRecord::Base
  def self.dataset
    sequel_db[table_name.to_sym].tap do |dataset|
      dataset.row_proc = lambda{|row_hash| instantiate(row_hash.stringify_keys)}
    end
  end

  def self.sequel_db
    # get a Sequel::Database connection however you want it
  end
end

Now if you have

1
2
3
class Product < ActiveRecord::Base
  # Lots of validators, scopes, and the rest of the model stuff
end

you can do things like this in the controller, using Sequel’s querying capabilities…

1
@products = Product.dataset.filter( name:/^some prefix/ )

…and naturally this in the view

1
2
3
4
-# Obviously product is an instance of Product
- @products.each |product|
  %tr
    %td= product.name

Drawbacks:

  • You’ll end up having 2 db connections – one for ActiveRecord and one for Sequel. Which is fine unless you have a transaction and one connection does a write which you’re expecting to show up in the other connection. Like in unit tests. So turn transactional fixtures off for those.

  • Calling ActiveRecord::Base.instantiate skips callbacks. I’m sure there’s an easy way to hook them back in again.

Comments