首页 > 解决方案 > 索引未显示搜索结果

问题描述

[编辑] 更改了一些功能以使其更清晰。我正在尝试创建一个搜索功能,用户可以在其中输入查询,并且 API(https://github.com/games-directory/api-giantbomb)返回匹配的项目。然而,尽管我搜索时没有弹出任何错误,但我的索引上没有出现任何内容。

我决定使用 Rails LIKE 功能在我的索引中返回查询结果,如下所示。

  def index
  if params[:query].present?
      sql_query = "name LIKE :query"
      @games = Game.where(sql_query, query: "%#{params[:query]}%")
    else
     flash[:notice] = "No Games Found"
    end
  end

它重定向到索引,但不显示任何游戏或 Flash 消息。这是索引:我的 index.html.erb 应该返回与查询匹配的游戏列表:

<h1>Test</h1>
<ul>
  <% @games.each do |game| %>
    <li><%= game.name %></li>
  <% end %>
</ul>

我可以看到“测试”文本,但在我进行搜索后没有其他内容。

作为参考,这是我的 GamesController 的其余部分。

class GamesController < ApplicationController
//Displays search results
  def index
  if params[:query].present?
      sql_query = "name LIKE :query"
      @games = Game.where(sql_query, query: "%#{params[:query]}%")
    else
     flash[:notice] = "No Games Found"
    end
  end

//Searches through API data
  def search
    @games = GiantBomb::Search.new().query(params[:query]).resources('game').limit(5).fetch
    render 'index'
  end


private

  def game_params
    params.require(:game).permit(:name, :search, :query)
  end
end

我的路线以防万一有任何影响。:

Rails.application.routes.draw do
  devise_for :users
  resources :games
  root to: 'pages#home'
  get '/search', to: 'games#search', as: :search
  get '/games', to: 'games#index', as: :index
end

我主页上的搜索栏:

    <div class="search-font"><h1>Build your Collection</h1></div>
    <div class="container">
      <div class="row">
        <div class="col-md-12 row">
          <%= form_tag index_path, method: :get do %>
          <div class="col-12 col-sm pr-sm-0">
            <%= text_field_tag :query,
              params[:query],
              class: "form-control input-lg",
              id: "typed-text" %>
          </div>
          <div class="input-group-btn ml-3">
            <%= submit_tag "Search", class: "btn btn-primary" %>
          </div>
          <% end %>
        </div>
      </div>
    </div>

这里有什么问题?我需要修改我的索引方法还是有其他问题?

标签: ruby-on-railsapisearch

解决方案


我在评论中添加了它,但看起来您需要确保传入正确的参数哈希结构,其中包含模型。

因此,{query: ‘your text’}您希望将其读取为,而不是通过 ,{game: {query: ‘your text’} }以便强大的参数game_params来获取它。您name的输入属性将从queryto更改为game[query]正确嵌套。


推荐阅读