heartcombo/has_scope

has_scope block is executed twice

patricklehmann opened this issue · 1 comments

Hi there

I've the following problem: I'm using has_scope 0.6.0 and rails 4.2.6. I want to add a query parameter for my index actions globally to execute a search. The search request should be persisted in database.

I'm doing this:

    has_scope :query do |controller, scope, value|
      if resource_class.relations['principal'].nil?
        scope.query(value)
      else
        principal = Backend::Principal.only(:id, :_slugs)
                                      .find(controller.params[:principal_slug])

        search_request = Search::Request::AdminUser.new(
          query: value,
          params: controller.params,
          admin_user_id: controller.current_admin_user.id,
          principal_id: principal.id
        )
        search_request.save!

        scope.query( value, { principal_id: principal.id } )
      end
    end

If my current resource_class has a relation :principal i want to create a Search::Request::AdminUser object. This works great. My problem is that the code is executed twice per request. I to /?query=audi and gets two Search::Request::AdminUser objects with query audi from the same time. Any suggestions?

Thanks a lot!

@patricklehmann sorry for the delay on looking into this - I couldn't reproduce your issue through the has_scope test suite (below is a diff of the test case I tried to wrote). Can you please try to replicate your issue into a test case or sample app? Thanks!

diff --git a/test/has_scope_test.rb b/test/has_scope_test.rb
index 278b2f9..644a7ba 100644
--- a/test/has_scope_test.rb
+++ b/test/has_scope_test.rb
@@ -27,6 +27,12 @@ class TreesController < ApplicationController
     scope.by_given_category(controller.object_id, value + "_id")
   end

+  has_scope :block_count do |controller, scope|
+    controller.block_called ||= 0
+    controller.block_called += 1
+    scope
+  end
+
   def index
     @trees = apply_scopes(Tree).all
   end
@@ -41,6 +47,8 @@ class TreesController < ApplicationController

   alias :edit :show

+  attr_accessor :block_called
+
   protected
     def restrict_to_only_tall_trees?
       true
@@ -332,6 +340,12 @@ class HasScopeTest < ActionController::TestCase
     assert_equal(:categories?, BonsaisController.scopes_configuration[:categories][:if])
   end

+  def test_scope_block_isnt_called_twice
+    Tree.expects(:all).returns([])
+    get :index, block_count: 123
+    assert_equal 1, @controller.block_called
+  end
+
   protected

     if ActionPack::VERSION::MAJOR == 5