Permalink
Browse files

Fix problem with belongs_to reload with some ugly monkey patching

  • Loading branch information...
lifo committed Sep 13, 2011
1 parent 7e6c610 commit a5da0708ba4f0e45b4f1622d5a29a15fe974a8be
Showing with 48 additions and 14 deletions.
  1. +4 −6 lib/sidekick/active_record.rb
  2. +41 −0 lib/sidekick/association_proxy_monkey.rb
  3. +1 −4 lib/sidekick/reload.rb
  4. +2 −4 test/basic_test.rb
@@ -41,6 +41,10 @@ def to_a_with_kick
alias_method_chain :to_a, :kick
end
+if ActiveRecord::VERSION::STRING < '3.1' && !ActiveRecord::Associations::AssociationProxy.instance_methods.include?(:load)
+ require 'sidekick/association_proxy_monkey'
+end
+
[
ActiveRecord::Associations::BelongsToAssociation,
ActiveRecord::Associations::HasManyAssociation,
@@ -50,12 +54,6 @@ def to_a_with_kick
ActiveRecord::Associations::HasManyThroughAssociation
].each do |association_klass|
association_klass.send :include, Sidekick::Target
-end
-
-[
- ActiveRecord::Associations::HasManyAssociation,
- ActiveRecord::Associations::HasManyThroughAssociation
-].each do |association_klass|
association_klass.send :include, Sidekick::Reload
end
@@ -0,0 +1,41 @@
+# Please remove me as soon as you can - __FILE__
+
+class ActiveRecord::Associations::AssociationProxy
+ def load
+ load_target unless loaded?
+ self unless @target.nil?
+ end
+
+ def reload
+ reset
+ load
+ end
+end
+
+module Sidekick
+ module MonkeyAssociationAccessor
+ def association_accessor_methods(reflection, association_proxy_class)
+ super(reflection, association_proxy_class)
+
+ redefine_method(reflection.name) do |*params|
+ force_reload = params.first unless params.empty?
+ association = association_instance_get(reflection.name)
+
+ if association.nil? || force_reload
+ association = association_proxy_class.new(self, reflection)
+ retval = force_reload ? reflection.klass.uncached { association.reload } : association.load
+ if retval.nil? and association_proxy_class == BelongsToAssociation
+ association_instance_set(reflection.name, nil)
+ return nil
+ end
+ association_instance_set(reflection.name, association)
+ end
+
+ association.target.nil? ? nil : association
+ end
+
+ end
+ end
+end
+
+ActiveRecord::Base.send :extend, Sidekick::MonkeyAssociationAccessor
View
@@ -6,10 +6,7 @@ def self.included(base)
def reload_with_kick
@owner._parent_record_set = nil
-
- reset
- load_target
- self unless @target.nil?
+ reload_without_kick
end
end
end
View
@@ -59,17 +59,15 @@ def test_belongs_to
end
def test_belongs_reload
- flunk
-
- assert_queries(3) do
+ assert_queries(4) do
# Query 1
posts = Post.all
hello_post = posts.detect {|p| p.title == 'Hello' }
# Query 2 - Load all the users
assert_equal 'Bob', hello_post.user.name
- # Query 3 - Reload Bob
+ # Query 3 & 4- Reload Bob. Also fires SHOW TABLES query.
assert_equal 'Bob', hello_post.user.reload.name
end
end

0 comments on commit a5da070

Please sign in to comment.