在Rails中显示来自API的搜索栏查询结果,通常涉及到以下几个基础概念和技术点:
解决方案:
class SearchController < ApplicationController
def index
@results = []
if params[:query]
response = HTTParty.get("https://api.example.com/search?q=#{params[:query]}")
@results = JSON.parse(response.body)['results']
end
end
end
content_for
或直接在模板中使用@results
变量来展示数据。<!-- app/views/search/index.html.erb -->
<%= form_tag search_path, method: :get do %>
<%= text_field_tag :query, params[:query] %>
<%= submit_tag 'Search' %>
<% end %>
<% if @results.any? %>
<ul>
<% @results.each do |result| %>
<li><%= result['title'] %></li>
<% end %>
</ul>
<% else %>
<p>No results found.</p>
<% end %>
解决方案:
在控制器中添加错误处理逻辑,例如使用rescue
来捕获异常并设置默认值或显示错误信息。
class SearchController < ApplicationController
def index
@results = []
begin
if params[:query]
response = HTTParty.get("https://api.example.com/search?q=#{params[:query]}")
@results = JSON.parse(response.body)['results']
end
rescue StandardError => e
logger.error "API request failed: #{e.message}"
# 设置默认值或显示错误信息
@results = [{ title: 'Error fetching data. Please try again later.' }]
end
end
end
领取专属 10元无门槛券
手把手带您无忧上云