Skip to content Skip to sidebar Skip to footer

How To Select Data From API Call Result In Rails?

I’m completely new to ruby on rails, I’m creating a simple article search application that would use the Guardian API and just display the news titles. It just needs to work l

Solution 1:

The response is some JSON, so you need to learn how to map through it and get the results that you want.

To see the data more clearly try printing it with:

puts JSON.pretty_generate(@results)

in your controller, then see the output in your rails console.

Anyway, you have a few options:

Option 1: Likely you just need to drill down further into @results in your view. In the JSON that is returned, the webTitles are nested, so changing the third line below should work. Also note on that line that I removed the = sign to prevent the return value from being displayed.

<% if @results != nil %>
  <ul>
  <% @results["response"]["results"].each do |r| %>
  <li><%= r["webTitle"] %></li>
  <% end %>
  </ul>
<% else %>
  <p>No results yet</p>
<% end %>

Option 2: You may consider getting the list of articles in your controller, which I think was your original intent and also is probably more "rails" like:

class SearchController < ApplicationController
    def search
        @app = GuardianApiClient.new
        @results = @app.query(params[:q])
        @articles = @results["response"]["results"].map do |article|
            article
        end
    end
end

In your view, then call render to a partial:

<%= render 'articles' %>

Then create a partial view called _articles.html.erb in whatever directory your other view is in, and then add some code to display each article:

<ul>
  <% @articles.each do |article| %>
    <li><%= article["webTitle"] %> <% link_to 'Link', article["webUrl"] %></li>
  <% end %>
<ul>

By separating out each article that was returned in the @articles array, it will probably be easier for you to get other attributes as well in a more readable way. As you can see, above I included a link to the actual article.


Post a Comment for "How To Select Data From API Call Result In Rails?"