Ruby 功能搜索栏

Ruby function search bar

我的搜索栏功能有问题,我想让它搜索我的食谱模型属性“成分”。当我将此代码放入其中时,它不会给我任何结果,搜索后只会出现一个空白的食谱页面。任何帮助都会很棒。 我在食谱 table.

中将配料作为文本

这是食谱里面的index.html

    <%= form_for "", url: recipes_path, role: "search", method: :get do %>
<%= text_field_tag :search, @search_term, placeholder: "Seach..." %>

<% 结束 %>

这是配方控制器

  def index
  @recipes = Recipe.all
  # @recipes =Recipe.search(params[:search])

  if params[:search]
    @search_term = params[:search]
    @recipes = @recipes.search_by(@search_term)
  end

结束

这是食谱模型函数

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)

有谁知道为什么不搜索食谱成分?提前谢谢你。

search_by方法中的插值错误。
当正确的是 "%#{search_term.downcase}%" 时,你写了 "%{search_term.downcase}%"。错过了 #!

def self.search_by(search_term)
    where("LOWER(ingredients) LIKE :search_term OR LOWER(title) LIKE :search_term",
    search_term: "%#{search_term.downcase}%")
end