2016-07-30 167 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卡路里:浮動' –