首页 > 解决方案 > 如何使用引用直通表的范围编写`has_many:through`?

问题描述

如何编写:has_many与 where 子句的关联,该子句引用另一个我也可以使用的表:includes

粗略地说,我想要的代码如下:

class User < ActiveRecord::Base
  has_many :as, -> {
    where('as.x >= bs.date_start and as.x <= bs.date_end')
  }, through: :bs
end

这在我实例化特定模型时有效。例如

> u = User.find(1)
> u.as.to_a
[...] # I get results I want

但是,我不能:includes在这个关联上使用:

> User.includes(:as).where(id: [1])
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'as.x' in 'where clause': SELECT `bs`.* FROM `bs` WHERE (as.x >= bs.date_start and as.x < bs.date_end) AND `bs`.`id` IN (1)

如何重写我的代码以便我可以:includes在我的关联中使用?


编辑:我尝试像这样重写关联,但没有奏效:

has_many, :as, -> (b) {
  where('as.x >= ? and as.x <= ?', b.date_start, bs.date_end)
}, through: bs

> u = User.find(1)
> u.as
NoMethodError: undefined method 'date_start' for #<User:...>

标签: ruby-on-railsactiverecordassociations

解决方案


我认为您需要.references(:as)在查询中添加它。User.includes(:as).references(:as).where(id: [1])

https://apidock.com/rails/ActiveRecord/QueryMethods/references


推荐阅读