假设我有两个模型,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
title和Category实施文本搜索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)
请参阅:在热切的关联上指定条件
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句