首页 > 解决方案 > 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.* FROM commentsWHERE (product.product_infos.name like '%Search_term%') ORDER BY commentsidDESC 限制 20 偏移量 0

我错过了什么?

标签: ruby-on-rails

解决方案


这应该可以解决问题。试试这个添加.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

推荐阅读