首页 > 解决方案 > 在 Rails 中显示来自 API 的搜索栏查询结果

问题描述

我正在尝试创建一个简单的应用程序,您可以在其中通过搜索栏从 API 中查找游戏。我正在使用 Giant Bomb API gem ( https://github.com/games-directory/api-giantbomb )。gem 似乎正在工作,因为我可以通过控制台调用东西。但是,我不太确定如何显示结果,或者我的搜索方法是否存在问题(可能)。

这是我的游戏控制器:

class GamesController < ApplicationController
//Display search results

  def index
  @games = Game.all.order('created_at DESC')
  @games = @games.search(params[:query]) if params[:query].present?
  end

//Searches through API and redirects to results on index.
  def search
    @games = GiantBomb::Search.new().query(params[:query]).resources('game').limit(5).fetch
    redirect_to index_path
  end


private

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

我主页上的搜索条码:

    <div class="search-font"><h1>Build your Collection</h1></div>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <%= form_tag search_path class: "row", method: :get do %>
          <div class="col-12 col-sm pr-sm-0">
            <%= text_field_tag :game,
              params[:game],
              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>

还有我的 index.html.erb 应该吐出游戏名称的地方。

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

搜索栏重定向,但没有发布任何内容。在我的控制台中,我可以执行 search.query('Mario') 然后 search.fetch 打印出结果,但我不确定如何在我的控制器中正确使用此功能。

[编辑] 这也是我的路线。

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

标签: ruby-on-railsapisearch

解决方案


redirect_to创建一个新请求,您需要使用render...

render 'index'

这样你就可以@games在视图中使用你的变量


推荐阅读