ruby-on-rails - Rails 包含与条件的多个关联
问题描述
我想实现下面的查询,但是遇到了一些麻烦。
这是关系。
Comment belongs_to Product
Product has_many Product_infos
以下是我需要实现的目标,
@comments = Comment.order(id: :desc)
.includes([product: :product_infos])
.where('product.product_infos.name like ?', "%#{params[:search]}%")
但它抛出了这个错误
Mysql2::Error: Unknown column 'product.product_infos.name' in 'where clause': SELECT
comments
.* FROMcomments
WHERE (product.product_infos.name like '%Search_term%') ORDER BYcomments
。id
DESC 限制 20 偏移量 0
我错过了什么?
解决方案
这应该可以解决问题。试试这个添加.references(:product_infos)
Comment
.order(id: :desc).includes([product: :product_infos])
.where('product_infos.name like ?', "%#{params[:search]}%")
.references(:product_infos)
.inspect
请参阅 API:http ://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-references
当您需要使用更直接的条件时,可以使用以下语法:
Comment
.includes([product: :product_infos])
.where(product_infos: {name: "another info on product one"})
.inspect
推荐阅读
- html - 博主移动视图上的代码格式被截断,没有滚动条选项
- ssas - 将 Model.bim 从 SQL Server 2017 转换为 2019
- azure - 如何使用 AzureRM cmdlet 删除存储帐户容器(blob),我的 power shell 版本是 5.1
- c# - `List`或`array`datastructer存储从数组c#中挑选的值?
- puppeteer - 是否可以使用 Chrome 83 版运行 Puppeteer?
- mysql - MySQL 过程/事件未完成执行。花了大约30分钟
- c# - Chrome 83 中取消的 HTTP 请求
- http - 使用 ErrorCode CANCEL 看到 http2 RST_STREAM 帧
- android - Android 上的 SQLite 数据库 - 如何删除它?
- parse-platform - Parseplatform:在不向客户端提供结果信息的情况下防止保存