如何通过引用直通表的作用域编写“ has_many:through`?

问题描述 投票:0回答:1

如何与一个引用另一个我也可以与: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-rails activerecord associations
1个回答
1
投票

我想如果需要在查询中添加.references(:as)User.includes(:as).references(:as).where(id: [1])

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

© www.soinside.com 2019 - 2024. All rights reserved.