Reputation: 611
I have two json files (info.json and images.json) in my Rails root directory. They are both an extraction from a web scraping project I have and which I've been doing with the Mechanize Gem.
So I have two Json files, one has info about Plants like this:
info.json
{
"Brazil":[
{"Jungle Plants":[bla bla bla ]},
{"Desert Plants":[ bla bla bla ]}],
"Egypt":[
{"Jungle Plants":[bla bla bla ]},
{"Desert Plants":[ bla bla bla ]}]
and so on...
}
And the other Json file has the images the country flags like this:
images.json
{
"images":
{
"Brazil":"link/to/flag_image.jpg",
"Egypt":"link/to/flag_image.jpg",
and so on...
}
}
My migration table:
class CreatePlants < ActiveRecord::Migration[5.2]
def change
create_table :plants do |t|
t.string :country_name
t.jsonb :plant_categories
t.string :flag_photo
t.timestamps
end
end
end
What I currently have:
json_file = File.open("#{Rails.root}/info.json").read
json_objects = JSON.parse(json_file).symbolize_keys
json_objects.each { |key, value| Plants.create!(country_name: key, plant_categories: value) }
In my seeds, how can I combine both JSON files and make them pair/match with the respective image flag and their data and save them in the DB? I will appreciate your help!
EDIT: The flag images are download in the same order as the info.json country information. I would like to know how can I combine both of the files and save them in the DB
Upvotes: 0
Views: 269
Reputation: 1407
The below should work:
info = JSON.parse(File.read("#{Rails.root}/info.json"))
images = JSON.parse(File.read("#{Rails.root}/images.json"))
info.each do |country_name, plants|
# Hope the Model name is singular here
plant = Plant.new(country_name: country_name, plant_categories: plants)
path = images['images'][country_name]
if path
# Read the file from remote URL like S3
# images['images'][country_name] - Will return the image URL on the key country_name
attachment = open(images['images'][country_name])
plant.flag_photo = attachment
end
plant.save!
end
Upvotes: 1