简体   繁体   中英

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:

  • active
  • orders (associated orders)

Orders:

  • created_at

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.

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