简体   繁体   中英

Rails apply boolean method to filter query results

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM