【发布时间】:2021-09-06 00:37:16
【问题描述】:
我是一名学习 Ruby on Rails 的新手。我应该从 url 读取和解析 csv 文件,然后将数据从 csv 注入数据库。然后通过这个数据库,我必须在 Rails 上创建一个 html 页表,包含并列出来自 csv 文件的信息。
我的控制器
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
我的迁移
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
我的 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?
感谢您的时间和精力。
【问题讨论】:
-
您需要使用
io.read.encode("UTF-8", Invalid: :replace, undef: :replace, replace: '?')来解决您可能遇到的编码问题...有关更多信息,请参阅stackoverflow.com/questions/13003287/…。 -
我用过'''{ |io| io.read.encode("UTF-8", invalid: :replace) } ''' 它对我有用。桌子也可以。我只剩下一个问题了。 ''' t.float :units_per_pound ''' 这个参数返回值 0.0 但在命令提示符下没问题。我不确定我现在应该编辑这个问题还是应该问一个新问题?
-
最好将其作为一个单独的问题提出,因为这是一个不同的问题。
标签: html ruby-on-rails ruby