Reputation: 63
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. I made a simple view, controller and a class that makes calls to external API, but the results don’t show up on my page and I’m puzzled. It just needs to work this way: a user enters the page, fills in the search form and views the news titles. I’m using httparty gem.
API consumer class:
#app/clients/guardian_api_client.rb
class GuardianApiClient
include HTTParty
API_KEY = ENV['GUARDIAN_CONTENT_API_KEY']
BASE_URL ="https://content.guardianapis.com/search?"
API_PARTIAL_URL = "api-key=#{API_KEY}"
def query(q)
request = HTTParty.get(BASE_URL+"q=#{q}&""api-key=#{API_KEY}")
puts request
end
end
Controller:
class SearchController < ApplicationController
def search
@app = GuardianApiClient.new
@results = @app.query(params[:q])
end
end
View:
<%= form_with(url: '/search') do |f| %>
<%= f.text_field :q %>
<%= f.submit 'search' %>
<% end %>
<% if @results != nil %>
<ul>
<%= @results.each do |r| %>
<li><%= r["webTitle"] %></li>
<% end %>
</ul>
<% else %>
<p>No results yet</p>
<% end %>
Routes:
Rails.application.routes.draw do
get '/search' => 'search#search'
post '/search' => 'search#search'
end
Upvotes: 2
Views: 365
Reputation: 23307
In the API client you print the results with puts
:
def query(q)
request = HTTParty.get(BASE_URL+"q=#{q}&""api-key=#{API_KEY}")
puts request
end
puts
returns nil
, so controller doesn't get the results. You need to return request from your query
method:
def query(q)
request = HTTParty.get(BASE_URL+"q=#{q}&""api-key=#{API_KEY}")
puts request
request
end
(ruby returns the result of the last call in the method).
Upvotes: 1