[英]Rails search through `has_many :through` text fields
Let say I have a two models with association has_many :through
between them. 假设我有两个具有
has_many :through
关联的模型has_many :through
它们之间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
I want to create search functionality using ActiveRecord for mySQL database, which allow users to implement text search on Recipe
title and Category name
. 我想使用ActiveRecord创建用于mySQL数据库的搜索功能,该功能允许用户对
Recipe
title和Category name
实施文本搜索。
Now I have just: 现在我只有:
@recipes = Recipe.where('title LIKE ?', "%#{params[:query]}%")
How can I modify this query to search through both title of recipe and it's category names? 如何修改此查询以搜索配方标题及其类别名称?
Recipe.includes(:categories).where('recipes.title LIKE :query or categories.name like :query', query: "%#{params[:query]}%").references(:categories)
请参阅: 在热切的关联上指定条件
You need to left join to the associated table and query the name on either table with OR
: 您需要离开联接到关联的表,并使用
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]}%")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.