首页 > 解决方案 > Rails 包含 where 条件

问题描述

我有两个模型:

用户.rb

class User < ApplicationRecord
  has_many :orders, inverse_of: :user, dependent: :restrict_with_exception
end

订单.rb

class Order < ApplicationRecord
  belongs_to :user, inverse_of: :orders
end

我正在使用includes这样的where

User.where(id: selected_salesmen.pluck(:id))
    .includes(:orders)
    .where("order.booked_at > ? AND order.booked_at < ?", 
           booked_at_gteq, 
           booked_at_lteq)

但是,它并没有给我所需usersorders. 任何解释为什么这不起作用?

标签: sqlruby-on-rails

解决方案


这可能会使方法includes和之间有些混淆joins,它们具有相关但非常不同的含义。

  • includes将预先加载相关记录,从而防止以后多次调用数据库。它主要用于性能调整。
  • joins将在您的数据库查询中包含对相关表的连接,这允许您基于相关模型构建条件。

请注意,要使用连接,您需要引用表名,而不是关系名。默认情况下,ActiveRecord 将连接到一个表,该表是模型的复数名称。

因此,更改包括连接和“订单”到“订单”:

User.where(id: selected_salesmen.pluck(:id))
    .joins(:orders)
    .where(
      "orders.booked_at > ? AND orders.booked_at < ?", 
      booked_at_gteq, 
      booked_at_lteq
    )

您可能还想检查是否也selected_salesmen.pluck(:id)返回了一些 id。


推荐阅读