I am a newbie studying Ruby on Rails. I am supposed to read and parse a csv file from a url then inject the data from csv to a database. Then via this database I must create a html page table on rails contains and lists the info from csv file.
My controller
require 'open-uri'
require 'csv'
class HmrcRatesController < ApplicationController
def index
@hmrc_rates = HmrcRate.all
end
def new
csv_text = URI.open('https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/988629/exrates-monthly-0621.csv') { |io| io.read.encode("UTF-8", invalid: :replace) }
csv = CSV.parse(csv_text, :headers=>true)
csv.each_with_index do |row, i|
HmrcRate.create(country: row["Country/Territories"], currency: row["Currency"], curr_code: row["Currency Code"], units_per_pound: row["Units Per £"], start_date: row["Start Date"], end_date: row["End Date"])
puts "#{i}. #{row}"
puts "***********************" #To seperate rows in command line this will go.
# HmrcRate.create!(row.to_hash) #This didn't work don't know why
end
redirect_to hmrc_rates_path, notice: "HMRC rates created"
end
end
My Migration
class CreateHmrcRates < ActiveRecord::Migration[6.0]
def change
create_table :hmrc_rates do |t|
t.string :country
t.string :currency
t.string :curr_code
t.float :units_per_pound
t.datetime :start_date
t.datetime :end_date
t.timestamps
end
end
end
My Index HTML
<h1>HmrcRates</h1>
<%= link_to "Get Rates", new_hmrc_rate_path %>
#I NEED THIS BIT HERE. HOW CAN I APPLY MY DATABASE TO HTML LIKE AN EXCEL TABLE?
Thank you for your time and effort.