【发布时间】:2021-02-23 13:36:09
【问题描述】:
[编辑] 更改了一些功能以使其更清晰。 我正在尝试创建一个搜索功能,用户可以在其中输入查询,并且 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>
这里有什么问题?我需要修改我的索引方法还是有其他问题?
【问题讨论】:
-
欢迎来到 Stackoverflow。目前还不清楚你在这里实际问的是什么以及为什么你会期望它起作用。您正在控制器中定义方法
search,但您正在使用不同的签名在模型上调用Game.search(params[:query])。也不要只写“阅读后”-“我试过谷歌搜索”等,这很蹩脚。列出你实际研究过的内容,因为它提供了关于你哪里出错的重要线索。 -
我继续编辑我的问题以使其更清楚。我试图让索引显示 API 数据的搜索结果。我修改了索引,但没有看到搜索结果。
-
所以,当您单击搜索表单上的提交按钮时,它会向游戏控制器上的索引方法发出 get 请求,对吗?一方面,你定义了
game_params,这很好,你应该使用强大的参数,但你没有在任何地方使用它。不过,就目前而言,您应该仍然可以访问params[:query]。您是否使用任何调试工具,例如 byebug 或 pry?我会尝试在您的 index 方法中折腾一个并检查 @games 是否为空。 -
当我运行 byebug 时,我的索引似乎正在工作:SELECT "games".* FROM "games" WHERE (name LIKE '%QueryText%') LIMIT $1 [["LIMIT", 11]] .但是,当我将参数更改为 game_params 时,我得到: "param is missing or the value is empty: game" 。那么 :game 是否是空的?
-
所以,看看正在发送的参数哈希。您当前正在传递像
{query: ‘text you entered’}这样的参数散列,但是使用强参数并使用game_params,您应该传递一个以相关模型开头的散列,比如{game: {query: ‘text you entered’} }。尝试将该文本字段从query更改为game[query]that 并查看它是否有效。
标签: ruby-on-rails api search