Home > OS >  Ruby on Rails: How to 1) READ JSON from URL, then 2) GET the desired data, and 3) ADD create new rec
Ruby on Rails: How to 1) READ JSON from URL, then 2) GET the desired data, and 3) ADD create new rec

Time:09-16

Hi I'm new to Ruby on Rails and I want to:

  1. READ JSON from URL
  2. GET the desired data
  3. ADD (create) new record to the database

1. READ JSON from URL

I have an URL that returns JSON data. You can see it here. How to read that from view (.html.erb) and controller (.rb)?

I've read this but I didn't know where and how to use it.

2. GET the desired data

If you see this json link, you'll find that there's a lot of data in it. I just want to get some of the data like product_name, image_url, description. How can I extract them?

3. ADD (create) new record to the database

I used rails g scaffold ... to create the CRUD by default. But in this case, I cannot use that. The new record must be created based on the submitted URL, not by inputting it manually.

How to do this in controller (.rb):

# POST /products or /products.json
def create

  # I want something like this to read JSON
  parsedJson = JSON_fromURL('http://world.openfoodfacts.org/api/v0/product/3661112054465.json')

  # and I want something like this to create record
  product_params.product_name = parsedJson['product_name']
  product_params.image_url = parsedJson['image_url']
  product_params.description = parsedJson['description']
  @product = Product.new(product_params)

  ...
  
end

CodePudding user response:

you can use httparty gem for making API call and getting results from it as below:

def create
  URL = "http://world.openfoodfacts.org/api/v0/product/3661112054465.json"
  response = HTTParty.get(url).parsed_response 
  
  product_params = {
    name: response['product']['product_name'], 
    image_url = response['product']['image_url'],
    description = response['product']['description']
  }
  @product = Product.new(product_params)
  @product.save
end

Please read more about HTTParty Gem

I hope this will help you.

CodePudding user response:

So, I actually found the answer myself.

1. READ JSON from URL

I found this answer from stackoverflow, but I forgot the source link.

To read the JSON from URL, do this:

In controller .rb:

def index
    ...
    require 'net/http'
    source = "http://your_link.json"
    resp = Net::HTTP.get_response(URI.parse(source))
    data = resp.body
    data = JSON.parse(data)
    ...
end

Still in controller, to debug the JSON in data variable, I used abort combined with .inspect like this:

abort data.inspect

2. GET the desired data

This is actually same for almost all programming language. To access JSON data variable in controller .rb, do this:

@product = Product.new
@product.brands = data["brands"]
@product.categories = data["categories"]
@product.image_url = data["image_url"]

3. ADD (create) new record to the database

In controller .rb:

@product.save
  • Related