我的搜索栏功能有问题,我希望它搜索我的食谱模型属性“配料”。当我把这段代码放进去时,它不会给我任何结果,只会在搜索后给我一个空白的食谱页面。任何帮助都会很好。我把配料作为文本放在配方表中。
这在recipe index.html中
<%= form_for "", url: recipes_path, role: "search", method: :get do %>
<%= text_field_tag :search, @search_term, placeholder: "Seach..." %>
<%end%>
这是配方控制器
def index
@recipes = Recipe.all
# @recipes =Recipe.search(params[:search])
if params[:search]
@search_term = params[:search]
@recipes = @recipes.search_by(@search_term)
end
结束
这是recipes模型函数
def self.search_by(search_term)
where("LOWER(ingredients) LIKE :search_term OR LOWER(title) LIKE :search_term",
search_term: "%{search_term.downcase}%")
end
这也是执行搜索时的命令行:
Started GET "/recipes?search=chicken" for 127.0.0.1 at 2021-07-09 07:52:57 -0400
Processing by RecipesController#index as HTML
Parameters: {"search"=>"chicken"}
Rendering layout layouts/application.html.erb
Rendering recipes/index.html.erb within layouts/application
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 3], ["LIMIT", 1]]
↳ app/views/recipes/index.html.erb:13
Recipe Load (0.2ms) SELECT "recipes".* FROM "recipes" WHERE (LOWER(ingredients) LIKE '%{search_term.downcase}%' OR LOWER(title) LIKE '%{search_term.downcase}%')
↳ app/views/recipes/index.html.erb:70
Rendered recipes/index.html.erb within layouts/application (Duration: 5.0ms | Allocations: 2463)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_alerts.html.erb (Duration: 0.1ms | Allocations: 41)
Rendered layout layouts/application.html.erb (Duration: 11.0ms | Allocations: 7781)
Completed 200 OK in 12ms (Views: 11.1ms | ActiveRecord: 0.3ms | Allocations: 8360)
有人知道为什么不搜索配方成分吗?先谢谢你。
1条答案
按热度按时间4nkexdtk1#
“搜索方法”中的插值错误。
你写的
"%{search_term.downcase}%"
当正确的"%#{search_term.downcase}%"
. 错过了#
!