1

I have some complicated boolean methods that I want to use as a filter for Database query results. I want a solution that would work for both SQL and Mongoid DB.

class Bar < ActiveRecord::Base OR include Mongoid::Document

    [field :some_field]

    def method1?
    ...
    end

    def method1?
    ...
end

This is what I would like to write :

def self.someFunc
    Bar.where(some_field: some_value).filter(method1?, method2?)
end

Is there a simpler way than do do that :

def self.someFunc
    results = Array.new
    Bar.where(some_field: some_value).each do |result|
       if result.filter1? && result.filter2?
           results << result
       end
    end
    results
end
tshepang
  • 12,111
  • 21
  • 91
  • 136
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164
  • What is an example of the content of these methods? Can you make them into scopes that you can chain onto your `where` call? – jstim Aug 28 '14 at 19:13
  • For now it's just a regexp (`def method1? {self.role.downcase =~ /.*tr[e|é]so.*/ }`) But later I might want to add several other stuff. I read on other posts that I could use SQL queries like `Where role like "%Regexp%` but if possible I'd rather use ruby/rails stuff. – Cyril Duchon-Doris Aug 28 '14 at 20:17
  • Also, I don't care at all about performance. I'd rather have easily understandable and inefficient code than complicated efficient code. – Cyril Duchon-Doris Aug 28 '14 at 20:21
  • So basically, I want "scopes" but where the filtering is done after the query by the rails framework. – Cyril Duchon-Doris Sep 15 '14 at 18:15
  • Yea, I would lean toward adding a scope for each test you want to do, then you can chain whichever combination you want to use. The scopes will be little snippets of SQL or ActiveRecord methods, depending on what you need to write. Doing it in scopes means the filtering is done in the database, instead of you writing methods that loop over the whole record collection in ruby, which is substantially slower. – jstim Sep 15 '14 at 18:36
  • Actually I found an answer that mentions a $where that I can use for Mongoid queries (q: http://stackoverflow.com/questions/8136652/query-mongodb-on-month-day-year-of-a-datetime). I think that's what I need (performance isn't the issue) – Cyril Duchon-Doris Sep 24 '14 at 20:58

1 Answers1

1

Okay actually I've used three different techniques to achieve my goal : named_scopes, boolean functions, and array filtering

This link explains array filtering

In my code (using both named_scopes, regexp, and filtering) :

# Named scopes :
scope :current_team, ->{ where(mandate: Constants.mandate)}

# Boolean function :
def prez?
    self.role.downcase =~ /.*pre[sident|z].*/
end

# Array filtering : 
def self.prez
    Bar.current_team.select {|admin|admin.prez?}
end.first
Community
  • 1
  • 1
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164