我有一个功能性红宝石应用程序,我通过遵循几乎没有或没有FUS的Baserail教程创建的功能性Ruby应用程序,我试图通过遵循本教程将多个记录上传到数据库中。似乎很直截了当,并认为我可以在几分钟之内实现。
问题是当我上传CSV文件时,我收到了我上传成功的通知,首先,仅创建一个记录,其次创建的记录是空的。
我搜索和搜索,尝试了其他教程并最终遇到了同样的问题……我基本上是在Wits End。请参阅下面的代码段:
医院.rb
class Hospital < ApplicationRecord
mount_uploader :image, ImageUploader
searchkick
has_many :reviews
#validates :name, :address, :phone, :image, presence: true
#validates :website, format: { with: /Ahttps?://.*z/,
#message: "must start with http:// or https://" }
#validates :phone, numericality: {
#only_integer: true,
#message: "must be land line(7 digits) or Gsm(11 digits)"
#}
end
HOUSITAT_CONTROLLER.RB
class HospitalsController < ApplicationController
...
def import
Hospital.import(params[:file])
end
...
def create
@hospital = Hospital.new(hospital_params)
respond_to do |format|
if @hospital.save
format.html { redirect_to @hospital, notice: 'Hospital was successfully created.' }
format.json { render :show, status: :created, location: @hospital }
else
format.html { render :new }
format.json { render json: @hospital.errors, status: :unprocessable_entity }
end
end
end
private
def hospital_params
params.require(:hospital).permit(:name, :address, :city_town, :state, :phone, :website, :safe_care, :jci, :cohsasa, :best_known_4, :image )
end
end
Rails Server上的输出
Started POST "/hospitals" for ::1 at 2017-06-22 12:58:09 +0100
Processing by HospitalsController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxx==",
"hospital"=>{"name"=>"",
"address"=>"", "city_town"=>"", "state"=>"", "phone"=>"", "website"=>"",
"safe_care"=>"", "jci"=>"", "cohsasa"=>"", "best_known_4"=>""}, "file"=>#
<ActionDispatch::Http::UploadedFile:0x007fe064b78918 @tempfile=#
<Tempfile:/var/folders/xh/hv6bwdzs3cx4ws9x42n3gsn00000gn/
T/RackMultipart20170622-80750-147ctbc.csv>, @original_filename="Test.csv",
@content_type="text/csv", @headers="Content-Disposition: form-data;
name="file"; filename="Test.csv"rnContent-Type: text/csvrn">,
"commit"=>"Import CSV"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ?
ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Can't verify CSRF token authenticity.
(0.1ms) begin transaction
(0.1ms) commit transaction
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "hospitals" ("name", "address", "phone", "website",
"created_at", "updated_at", "city_town", "state", "jci", "cohsasa",
"best_known_4", "safe_care") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
[["name", ""], ["address", ""], ["phone", ""], ["website", ""], ["created_at",
2017-06-22 11:58:09 UTC], ["updated_at", 2017-06-22 11:58:09 UTC],
["city_town", ""], ["state", ""], ["jci", ""], ["cohsasa", ""],
["best_known_4", ""], ["safe_care", ""]]
(0.8ms) commit transaction
Hospital Store (170.8ms) {"id":53}
Redirected to http://localhost:3000/hospitals/53
Completed 302 Found in 188ms (Searchkick: 170.8ms | ActiveRecord: 1.9ms)
您的代码正好表现出您的写作方式:
首先,仅创建一个记录 ...
是的。因为您从不打电话:
Hospital.import(params[:file])
它在您的import
操作中,但您永远不会从create
操作中调用它。当教程说:
步骤:3
在您的控制器中添加块
这并不意味着"您喜欢的任何旧地方,它将神奇地称为"。您必须实际呼叫逻辑。但是,你没有。因此,您的应用程序对CSV文件没有任何作用。这正是您告诉它与CSV文件进行的。
(另外,您的Hospital
类没有导入类方法。
其次创建的记录是空...
是的。就像您写的那样。
正如您在控制台中看到的那样,您的医院参数为空:
Started POST "/hospitals" for ::1 at 2017-06-22 12:58:09 +0100
Processing by HospitalsController#create as HTML
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxx==",
"hospital"=>{
"name"=>"",
"address"=>"",
"city_town"=>"",
"state"=>"",
"phone"=>"",
"website"=>"",
"safe_care"=>"",
"jci"=>"",
"cohsasa"=>"",
"best_known_4"=>""
},
"file"=>#<ActionDispatch::Http::UploadedFile:0x007fe064b78918 @tempfile=#
所以,当您这样做时:
@hospital = Hospital.new(hospital_params)
然后:
if @hospital.save
...
else
...
end
好吧,您刚刚告诉您的申请以创建空白记录,并且它很合适(特别是因为您已删除了所有验证(。
所以...写医院。iMport方法(请参阅教程的步骤4(类似的内容:
class Hospital < ApplicationRecord
mount_uploader :image, ImageUploader
searchkick
has_many :reviews
#validates :name, :address, :phone, :image, presence: true
#validates :website, format: { with: /Ahttps?://.*z/,
#message: "must start with http:// or https://" }
#validates :phone, numericality: {
#only_integer: true,
#message: "must be land line(7 digits) or Gsm(11 digits)"
#}
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Hospital.create! row.to_hash
end
end
end
在您的控制器中称其为:
def create
import if params[:file] # <= this here is the call to your import method
@hospital = Hospital.new(hospital_params)
respond_to do |format|
if @hospital.save
format.html { redirect_to @hospital, notice: 'Hospital was successfully created.' }
format.json { render :show, status: :created, location: @hospital }
else
format.html { render :new }
format.json { render json: @hospital.errors, status: :unprocessable_entity }
end
end
end
添加您的验证。您将在途中更接近。
尝试以下代码中的代码以导入csv ini db并在控制器中称为:
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(2)
(3..spreadsheet.last_row).each do |i|
row = spreadsheet.row(i) #Hash[[header, spreadsheet.row(i)].transpose]
f1= from = row[0]
f2 = row[1]
f3 = row[2]
ModelName.create({f1: f1, ... })
end
end