我正在开发轨道上的红宝石食物应用程序,需要从食物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页面的卡路里值
?索引 –
@ 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
的卡路里值食物模型中的卡路里值,当我构建,所以它在food.calorie提供错误是否有可能现在添加它? – coder