2016-07-30 56 views
0

我正在开发轨道上的红宝石食物应用程序,需要从食物api获取食物的卡路里值。在我的控制器中,我得到了JSON响应,但是我无法解析和显示index.html.erb文件中食物的卡路里值这里是我的控制器代码。如何在ruby中使用httparty显示json和解析json

require 'rubygems' 
require 'httparty' 

class FoodsController < ApplicationController 

    def index 
    @foods = Food.all 
    end 

    def show 
    @food = Food.find(params[:id]) 
    end 

    def new 
    @food = Food.new 
    end 

    def edit 
    @food = Food.find(params[:id]) 
end 

def create 
    @food = Food.new(food_params) 

    @response = HTTParty.get('http://api.nutritionix.com/v1_1/search/'[email protected]+'?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&appId=696d1ad4&appKey=aec2c4766d40d7f6346ed89d5d82fe75') 
    @http_party_json = JSON.parse(@response.body) 

    if @food.save 
    redirect_to foods_path 
    else 
    render 'new' 
    end 
end 


def update 
    @food = Food.find(params[:id]) 

    if @food.update(food_params) 
    redirect_to @food 
    else 
    render 'edit' 
    end 
end 

def destroy 
    @food = Food.find(params[:id]) 
    @food.destroy 

    redirect_to foods_path 
end 

private 
def food_params 
    params.require(:food).permit(:name, :quantity) 
end 

end 

任何建议是非常值得欢迎的,因为我对计算器新手,所以不知道正确的编辑,请原谅!帮助我如何显示HTML页面的卡路里值

+0

?索引 –

+0

@ mohamed-ibrahim感谢您的编辑。我想提取食物的卡路里值,例如牛奶在这个网址https://api.nutritionix.com/v1_1/search/Milk?fields=item_name%2Citem_id%2Cbrand_name% 2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&APPID = 696d1ad4&APPKEY = aec2c4766d40d7f6346ed89d5d82fe75并显示@穆罕默德-ITD法在对象被创建后 – coder

+0

的卡路里值食物模型中的卡路里值,当我构建,所以它在food.calorie提供错误是否有可能现在添加它? – coder

回答

0

您可以添加新的功能,以Food模式,让你的卡路里:在你的index.erb超过foods收集

class Food 

def calorie 
    response = HTTParty.get("http://api.nutritionix.com/v1_1/search/#{self.name}?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&appId=696d1ad4&appKey=aec2c4766d40d7f6346ed89d5d82fe75") 
    json = JSON.parse(response.body) 
end 
end 

,然后简单,如果你循环你做到以下几点:

<% @foods.each do |food| %> 
    <%= food.name %> 
    <%= food.calorie %> 
<% end %> 

,但在这种情况下的表现也不会好,因为你为每个显示数据的时间每个项目的远程访问,从而热量值始终是同样的食物相同,则后它创造的哟ü可以做远程查询和热量存储calorie属性,在Food模型

你可以做到以下几点:要在查看数据,行动

class Food < ActiveRecord::Base 
    before_create :set_calorie 

    private 
    def set_calorie 
    response = HTTParty.get("http://api.nutritionix.com/v1_1/search/#{self.name}?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&appId=696d1ad4&appKey=aec2c4766d40d7f6346ed89d5d82fe75") 
    self.calorie = JSON.parse(response.body) 
    end 
end 
+0

创建动作我没有定义的在index.html.erb文件 – coder

+0

我是新来红宝石学习的教程也没有有用的和简单的教程:( – coder

+0

检查http://api.rubyonrails.org/classes/ActiveRecord/Migration.html 它将轨道克迁移add_calorie_to_foods卡路里:浮动' –