ruby-on-rails - 在 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
解决方案
redirect_to
创建一个新请求,您需要使用render
...
render 'index'
这样你就可以@games
在视图中使用你的变量
推荐阅读
- c++ - 在使用邻接矩阵存储的无向图中查找和打印循环
- android - Android:两个依赖,每个依赖同一个组件,触发DexArchiveMergerException
- python - 基数为 10 的 int() 的无效文字:来自 ajax 的表单数据
- django-templates - 如何从 django 获取渲染的模板?-pdfkit
- javascript - JavaScript:将背景图像保存到用户磁盘
- extjs - ExtJS 6——在视图模型中获取存储
- nhibernate - 查询中的 NHibernate 集合属性(非流畅)
- vue.js - vuejs - 在计算内部更改返回值
- java - Android:如何让片段仅在地图加载完成时出现?
- python - 将值从一个数据帧提取到另一个数据帧