Permalink
Browse files

Fix association preloading in rails 3.2

  • Loading branch information...
1 parent 93a0f95 commit f050d901c911950c11f1412057869f96a3ce5304 @libc committed Feb 7, 2012
View
@@ -183,8 +183,19 @@ def on_master(&block)
ActiveRecord::Base.extend(DbCharmer::ActiveRecord::DbMagic)
# Setup association preload magic
-require 'db_charmer/active_record/association_preload'
-ActiveRecord::Base.extend(DbCharmer::ActiveRecord::AssociationPreload)
+if DbCharmer.rails32?
+ require 'db_charmer/rails32/active_record/preloader/association'
+ ActiveRecord::Associations::Preloader::Association.send(:include, DbCharmer::ActiveRecord::Preloader::Association)
+ require 'db_charmer/rails32/active_record/preloader/has_and_belongs_to_many'
+ ActiveRecord::Associations::Preloader::HasAndBelongsToMany.send(:include, DbCharmer::ActiveRecord::Preloader::HasAndBelongsToMany)
+else
+ require 'db_charmer/active_record/association_preload'
+ ActiveRecord::Base.extend(DbCharmer::ActiveRecord::AssociationPreload)
+
+ # Open up really useful API method
+ ActiveRecord::AssociationPreload::ClassMethods.send(:public, :preload_associations)
+end
+
class ::ActiveRecord::Base
class << self
@@ -0,0 +1,21 @@
+module DbCharmer
+ module ActiveRecord
+ module Preloader
+ module Association
+ extend ActiveSupport::Concern
+ included do
+ alias_method_chain :build_scope, :db_magic
+ end
+
+ def build_scope_with_db_magic
+ if model.db_charmer_top_level_connection? || reflection.options[:polymorphic] ||
+ model.db_charmer_default_connection != klass.db_charmer_default_connection
+ build_scope_without_db_magic
+ else
+ build_scope_without_db_magic.on_db(model)
+ end
+ end
+ end
+ end
+ end
+end
@@ -0,0 +1,23 @@
+module DbCharmer
+ module ActiveRecord
+ module Preloader
+ module HasAndBelongsToMany
+ extend ActiveSupport::Concern
+ included do
+ alias_method_chain :records_for, :db_magic
+ end
+
+ def records_for_with_db_magic(ids)
+ if model.db_charmer_top_level_connection? || reflection.options[:polymorphic] ||
+ model.db_charmer_default_connection != klass.db_charmer_default_connection
+ records_for_without_db_magic(ids)
+ else
+ klass.on_db(model) do
+ records_for_without_db_magic(ids)
+ end
+ end
+ end
+ end
+ end
+ end
+end

4 comments on commit f050d90

Seems like this was removed in the general rails branch, and google found me this. Did you reimplement from how they seemed to do it before, or just make it up again?

Owner

libc replied Mar 27, 2012

It wasn't removed in the rails master. I used the word 'reimplement' because it was removed in this project (db-charmer) before.

http://edgeapi.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-preload and http://edgeapi.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-includes are still there in master

Thanks for the link, I appreciate it :)

Any idea on the difference between preload and includes?

Please sign in to comment.