Html 如何在rails中从API调用结果中选择数据?

Html 如何在rails中从API调用结果中选择数据?,html,ruby-on-rails,ruby,Html,Ruby On Rails,Ruby,我是RubyonRails的新手,我正在创建一个简单的文章搜索应用程序,它将使用Guardian API并只显示新闻标题。它只需要这样工作:用户进入页面,填写搜索表单并查看新闻标题 我只想简单地选择请求结果的“webTitle”键,并将它们的值显示为列表项,但我得到了大量数据,我不知道如何才能做到这一点 以下是请求结果: {"response"=>{"status"=>"ok", "userTier"=>"developer", "total"=>2153270, "st

我是RubyonRails的新手,我正在创建一个简单的文章搜索应用程序,它将使用Guardian API并只显示新闻标题。它只需要这样工作:用户进入页面,填写搜索表单并查看新闻标题

我只想简单地选择请求结果的“webTitle”键,并将它们的值显示为列表项,但我得到了大量数据,我不知道如何才能做到这一点

以下是请求结果:

{"response"=>{"status"=>"ok", "userTier"=>"developer", "total"=>2153270, "startIndex"=>1, "pageSize"=>10, "currentPage"=>1, "pages"=>215327, "orderBy"=>"relevance", "results"=>[{"id"=>"books/2017/jul/16/fall-down-7-times-get-up-8-naoki-higashida-review-autism", "type"=>"article", "sectionId"=>"books", "sectionName"=>"Books", "webPublicationDate"=>"2017-07-16T06:00:13Z", "webTitle"=>"Fall Down 7 Times Get Up 8 review – a window on the world of autism", "webUrl"=>"https://www.theguardian.com/books/2017/jul/16/fall-down-7-times-get-up-8-naoki-higashida-review-autism", "apiUrl"=>"https://content.guardianapis.com/books/2017/jul/16/fall-down-7-times-get-up-8-naoki-higashida-review-autism", "isHosted"=>false, "pillarId"=>"pillar/arts", "pillarName"=>"Arts"}, {"id"=>"football/2017/jul/07/gold-cup-2017-predictions-usa-mexico-costa-rica-football", "type"=>"article", "sectionId"=>"football", "sectionName"=>"Football", "webPublicationDate"=>"2017-07-07T09:00:08Z", "webTitle"=>"Gold Cup picks: USA to tip under-strength Mexico and in-form Costa Rica", "webUrl"=>"https://www.theguardian.com/football/2017/jul/07/gold-cup-2017-predictions-usa-mexico-costa-rica-football", "apiUrl"=>"https://content.guardianapis.com/football/2017/jul/07/gold-cup-2017-predictions-usa-mexico-costa-rica-football", "isHosted"=>false, "pillarId"=>"pillar/sport", "pillarName"=>"Sport"}, {"id"=>"world/2017/jul/15/stream-of-floating-bodies-near-mosul-raises-fears-of-reprisals-by-iraqi-militias", "type"=>"article", "sectionId"=>"world", "sectionName"=>"World news", "webPublicationDate"=>"2017-07-15T08:00:01Z", "webTitle"=>"Stream of floating bodies near Mosul raises fears of reprisals by Iraqi militias", "webUrl"=>"https://www.theguardian.com/world/2017/jul/15/stream-of-floating-bodies-near-mosul-raises-fears-of-reprisals-by-iraqi-militias", "apiUrl"=>"https://content.guardianapis.com/world/2017/jul/15/stream-of-floating-bodies-near-mosul-raises-fears-of-reprisals-by-iraqi-militias", "isHosted"=>false, "pillarId"=>"pillar/news", "pillarName"=>"News"}]}}
API消费者类别:

app/clients/guardian_api_client.rb 类GuardianApiClient 包括HTTParty API_KEY=ENV['GUARDIAN_CONTENT_API_KEY'] 基本URL=https://content.guardianapis.com/search? API_PARTIAL_URL=API key={API_key} def查询 request=HTTParty.getBASE_URL+q={q}&api key={api_key} 提出请求 要求 终止 终止 控制器:

类SearchController<应用程序控制器 def搜索 @app=GuardianApiClient.new @结果=@app.queryparams[:q] 终止 终止 视图:

还没有结果

路线:

Rails.application.routes.draw do 获取“/search”=>“searchsearch” 发布“/search”=>“searchsearch” 终止
响应是一些JSON,因此您需要学习如何通过它进行映射并获得所需的结果

要更清楚地查看数据,请尝试使用以下工具打印:

把JSON.pretty_generate@results

在控制器中,然后在rails控制台中查看输出

无论如何,您有几个选择:

选项1:您可能只需要进一步深入查看视图中的@results。在返回的JSON中,webTitles是嵌套的,因此更改下面的第三行应该可以。还要注意,在那一行,我删除了=符号,以防止返回值显示

<% if @results != nil %>
  <ul>
  <% @results["response"]["results"].each do |r| %>
  <li><%= r["webTitle"] %></li>
  <% end %>
  </ul>
<% else %>
  <p>No results yet</p>
<% end %>
通过分离@articles数组中返回的每个项目,您可能更容易以更可读的方式获取其他属性。正如你所看到的,上面我包括了一个链接到实际的文章

class SearchController < ApplicationController
    def search
        @app = GuardianApiClient.new
        @results = @app.query(params[:q])
        @articles = @results["response"]["results"].map do |article|
            article
        end
    end
end
<%= render 'articles' %>
<ul>
  <% @articles.each do |article| %>
    <li><%= article["webTitle"] %> <% link_to 'Link', article["webUrl"] %></li>
  <% end %>
<ul>