搜索外部API时显示数据

时间:2016-03-26 16:57:21

标签: ruby-on-rails ruby api faraday

所以,我正在尝试搜索外部API(Nutrionix),并且无法弄清楚如何显示结果。

我目前有一个搜索表单

<form action = "/foods" method = "get">
  <div class = "field">
    <input type = "text" name = "searched_value" alt = "Search Foods" />
  </div>
  <div class = "btn">
    <input type = "submit" name ="btn" value = "Search Foods">
  </div>
</form>

然后我在我的FoodsController中:

class FoodsController < ApplicationController
  require 'faraday'
  require 'json'

  def search
    @searched_food = params[:searched_value].split(" ").join("%20")
    @response_body = Faraday.get("https://api.nutritionix.com/v1_1/search/#{@searched_value}?format=json?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=[MYAPPID]&appKey=[MYAPPKEY]").body
    @parsed_response = JSON.load(@response_body)
  end
end

我的相关路线是:

Rails.application.routes.draw do
  get 'food_form'  =>   'foods#food_form'
  get 'foods'       => 'foods#foods'
  get 'search'     =>     'foods#search'
end

然后回到链接到“添加食物”页面的页面,我目前正在尝试将内容显示出来,所以我有:

<div class = "description">
  <%= link_to "Add foods", food_form_path %>
  <%= @parsed_response%>
  <%= @response_body%>
  <%= @searched_food %>
</div>

我目前没有得到任何结果,因为只显示了表单的链接。但是,当我将控制器信息放在html页面上时,我可以看到结果,如果我自己去了nutrionix链接,我会得到结果。

非常感谢帮助。 :)

1 个答案:

答案 0 :(得分:0)

搜索表单 没有达到它应该执行的操作,因为它的action = "/foods"应该是action = "/foods/search"。改变它应该可以解决你的问题。

<form action = "/foods/search" method = "get">
  <div class = "field">
    <input type = "text" name = "searched_value" alt = "Search Foods" />
  </div>
  <div class = "btn">
    <input type = "submit" name ="btn" value = "Search Foods">
  </div>
</form>