ruby-on-rails - 如何使用引用直通表的范围编写`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:...>
解决方案
我认为您需要.references(:as)
在查询中添加它。User.includes(:as).references(:as).where(id: [1])
https://apidock.com/rails/ActiveRecord/QueryMethods/references
推荐阅读
- kotlin - 布尔检查 Kotlin 中可空字符串是否为空或空白
- reactjs - 如何创建用户上传头像功能
- python - 使用 python venv 时出现 ValueError
- asp.net - 如何设置 ComponentArt:NavBar 的最大宽度
- reactjs - 将状态和调度放入单独的上下文提供程序是否可以防止不必要的重新渲染?
- azure - 无法使用 Azure AD 和客户端凭据流为特定范围请求 OAuth2 令牌
- json - 动态配置 JSON 解析器的 Datastage 命令
- xslt - XSLT:根据当前上下文读取其他节点的值
- reactjs - react-dates 如何在 next.js 中加载 moment.js 异步
- flutter - Google Firestore 数据在两个不同的 Google 帐户中同时更新