Rails 搜索 `has_many :through` 文本字段

Rails search through `has_many :through` text fields

假设我有两个模型,它们之间有关联 has_many :through

class Category < ActiveRecord::Base
  has_many :category_recipes
  has_many :categories, through: :category_recipes

  validates :name, presence: true

class Recipe < ActiveRecord::Base
  has_many :category_recipes
  has_many :categories, through: :category_recipes

  validates :title, presence: true

我想使用 ActiveRecord 为 mySQL 数据库创建搜索功能,它允许用户在 Recipe 标题和类别 name 上实现文本搜索。

现在我刚刚:

@recipes = Recipe.where('title LIKE ?', "%#{params[:query]}%")

如何修改此查询以搜索菜谱标题及其类别名称?

Recipe.includes(:categories).where('recipes.title LIKE :query or categories.name like :query', query: "%#{params[:query]}%").references(:categories)

参见:Specifying Conditions on Eager Loaded Associations

您需要 left join 到关联的 table 并在 table 和 OR 上查询名称:

Recipe.joins("LEFT OUTER JOIN category_recipes ON category_recipes.recipe_id = recipes.id")
  .joins("LEFT OUTER JOIN categories ON categories.id = category_recipes.id")
  .where("recipes.title LIKE :q OR categories.name LIKE :q", q: "%#{params[:query]}%").uniq

嘿,这样试试

@recipes = Recipe.includes(:categories).where('title LIKE ? or categories.name LIKE ?', "%#{params[:query]}%","%#{params[:query]}%")