[编辑]更改了一些功能以使其更加清晰。 我正在尝试提供一个搜索功能,用户可以在其中输入查询,并且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>
这是什么问题?我需要修改索引方法还是有其他问题?
答案 0 :(得分:1)
我在评论中添加了它,但是看起来您需要确保您传入的是正确的参数哈希结构(包括模型)。
因此,您不想将其传递为{query: ‘your text’}
,而是将其读为{game: {query: ‘your text’} }
,以使game_params
的强大参数能够被使用。输入的name
属性将从query
更改为game[query]
以正确嵌套。