我有一個簡單的 Ruby on Rails 應用程式 CookBook,其中包含食譜。我有 2 張桌子(食譜和配料)。一個食譜有很多成分。
我正在嘗試實作一個簡單的搜索框,以便我可以過濾包含某些成分的食譜....
這些是表格:
create table recipes (id int, recipe_name varchar(100));
create table ingredients(id int, ingredient_name varchar(100), recipe_id int);
insert into recipes values
(1, 'my recipe 1'),
(2, 'my recipe 2');
(3, 'my recipe 3');
(4, 'my recipe 4');
insert into ingredients values
(1, 'Banana', 1),
(2, 'Milk', 1),
(3, 'Banana', 2),
(4, 'Milk', 2),
(5, '4 ? teaspoons baking powder', 2);
(6, '1 ? cups whole wheat flour', 4),
(7, 'Heavy Cream', 4);
(8, '? cup packed brown sugar', 3),
(9, 'Milk', 3);
(10, '2 teaspoons packed brown sugar', 4);
假設我在搜索框中輸入了兩種成分,例如“香蕉”和“牛奶”。然后我期望從包含這些單詞的成分表中獲取包含行的食譜......
這是我目前擁有的 recipes_controller 中的代碼:
def search
if params[:search].blank?
redirect_to recipes_path and return
else
@parameter = params[:search].downcase
@recipe_ids = Ingredient.search_ingredient(@parameter).pluck(:recipe_id)
@results = Recipe.where(id: @recipe_ids).paginate(page: params[:page], per_page: 26)
end
end
成分.rb中的代碼:
class Ingredient < ApplicationRecord
belongs_to :recipe
include PgSearch::Model
pg_search_scope :search_ingredient,
against: { ingredient_name: 'A' },
using: {
tsearch: {
dictionary: 'english', tsvector_column: 'searchable'
}
}
end
這樣做的問題是,如果我在搜索框中鍵入“香蕉牛奶”,我將不會在結果集中得到任何東西,因為它們在成分表中的不同行中,屬于食譜。在這種情況下,我至少應該得到 id 為 1 和 2 的食譜,因為它們都有這些成分
如果我只搜索一種成分,比如“牛奶”,那么我會得到所有包含該成分的食譜。
我該如何做到這一點?
先感謝您
uj5u.com熱心網友回復:
我建議你使用any_word屬性,看看這里的檔案 - https://github.com/Casecommons/pg_search#any_word
pg_search_scope :search_ingredient,
against: { ingredient_name: 'A' },
using: {
tsearch: {
any_word: true,
dictionary: 'english',
tsvector_column: 'searchable'
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/456262.html
標籤:轨道上的红宝石 红宝石 PostgreSQL
