Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calling will_ filter in scope fires another extra query #61

Open
vamsi-krishna-E0029 opened this issue Apr 3, 2015 · 0 comments
Open

Comments

@vamsi-krishna-E0029
Copy link

I have a scope defined in my model (say User) as

user.rb

scope :dummy_filter, lambda { |opts={}|
    options = { ftr:{}, page: 1, per_page: 50 }
    opts = options.merge opts
    filter(
      params: {query_hash: opts[:ftr], page: opts[:page], wf_per_page: opts[:per_page] },
      filter: :custom_filter
    )
  }

Now, when I access this scope I get two queries as,

> User.dummy_filter

User Load (12.7ms)  SELECT `users`.* FROM `users` ORDER BY users.id desc LIMIT 50 OFFSET 0

User Load (1.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`active` = 0 AND `users`.`account_id` = 1 ORDER BY users.id desc LIMIT 50 OFFSET 0

But when I use the will_filter directly I don't get the first query, I just get

> User.filter(params: {query_hash: opts[:ftr], page: opts[:page], wf_per_page: opts[:per_page] }, filter: :custom_filter)

User Load (1.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`active` = 0 AND `users`.`account_id` = 1 ORDER BY users.id desc LIMIT 50 OFFSET 0

which is the expected result. The same expected result can be seen when I define a class method similar to the scope in the user model.

def self.dummy_filter(opts={})
    options = { ftr:{}, page: 1, per_page: 50 }
    opts = options.merge opts
    filter(
      params: {query_hash: opts[:ftr], page: opts[:page], wf_per_page: opts[:per_page] },
      filter: :custom_filter
    )
end

In this case also I get the expected result.

> User.dummy_filter

User Load (1.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`active` = 0 AND `users`.`account_id` = 1 ORDER BY users.id desc LIMIT 50 OFFSET 0

My question is why is it misbehaving in Rails scope...or is it the intended behaviour?

Well, on debugging through the gem, I've tracked the problem down to these two lines (893,894) in /app/models/will_filter/filter.rb :

 recs = recs.page(page).per(per_page)
 recs.wf_filter = self

the line recs.wf_filter = self in particular. When I remove this line even the scope is behaving as expected. Not aware of after effects, if I remove this line.

Can someone throw some light over this issue, if it really is?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant