简体   繁体   中英

Rails search through `has_many :through` text fields

Let say I have a two models with association has_many :through between them.

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 .

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 :

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]}%")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM