Hendrik
Hendrik

Reputation: 4939

Convert this code into active record/sql query

I have the following code and would like to convert the request into a mysql query. Right now I achieve the desired result using a manual .select (array method) on the data. This should be possibile with a single query (correct me if I am wrong).

Current code:

  def self.active_companies(zip_code = nil)
    if !zip_code
      query = Company.locatable.not_deleted
    else
      query = Company.locatable.not_deleted.where("zip_code = ?", zip_code)
    end
    query.select do |company|
      company.company_active?
    end
  end
  # Check if the company can be considered as active
  def company_active?(min_orders = 5, last_order_days_ago = 15)
    if orders.count >= min_orders &&
      orders.last.created_at >= last_order_days_ago.days.ago &&
      active
        return true
    else
      return false
    end
  end

Explanation: I want to find out which companies are active. We have a company model and an orders model.

Data: Company:

Orders:

Upvotes: 0

Views: 63

Answers (1)

Erez Rabih
Erez Rabih

Reputation: 15808

I don't know if it is possible to make the company_active? predicate a single SQL query, but I can offer an alternative:

If you do:

  query = Company.locatable.not_deleted.includes(:orders)

All of the relevant orders will be loaded into the memory for future processing.

This will eliminate all the queries except for 2:

One to get the companies, and one to get all their associated orders.

Upvotes: 1

Related Questions