samedi 30 juillet 2016

how to display json and parse json in ruby using httparty

I am working on a food app in ruby on rails which requires to get calorie value of food item from food api.In my controller i am getting the JSON response but i am unable to parse and display the calorie value of food item in a index.html.erb file here is my controller code.

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://ift.tt/2aRHDbB'+@food.name+'?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

Any suggestions are highly welcome as i am newbie on stackoverflow so dont know proper editing forgive please! help me how to display calorie value in html page

Aucun commentaire:

Enregistrer un commentaire