我正在開發軌道上的紅寶石食物應用程序,需要從食物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