简体   繁体   English

将此代码转换为活动记录/ SQL查询

[英]Convert this code into active record/sql query

I have the following code and would like to convert the request into a mysql query. 我有以下代码,并希望将请求转换为mysql查询。 Right now I achieve the desired result using a manual .select (array method) on the data. 现在,我对数据使用手动.select(数组方法)达到了预期的结果。 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 created_at

I don't know if it is possible to make the company_active? 我不知道是否有可能使company_active? predicate a single SQL query, but I can offer an alternative: 断言单个SQL查询,但我可以提供另一种选择:

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: 这将消除除2之外的所有查询:

One to get the companies, and one to get all their associated orders. 一个获得公司,另一个获得所有相关订单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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