ruby-on-rails - Ruby on Rails MVC
问题描述
我正在开发一个基于 Ruby on Rails 和 Bootstrap 的应用程序。我被困在后端。我不清楚如何在作为活动记录的数据库中插入一些记录。我附上了我的数据库表的屏幕截图以及我的代码。我希望我能在这里得到正确的答案。
这是我的控制器:
class ImportCsvController < ApplicationController
before_action :require_user
before_action :require_admin
def index
end
# Import CSV file from Sysinflame
def import
end
def import_csv_datei
begin
@import_csvs = FileUploadInfo.new(params[:file])
if @import_csvs.read_save_csv(params[:file])
#Import Successful
user=current_user.user_name
time = Time.now
FileUploadInfo.import_file(params[:file],time.to_formatted_s(time),"erfolgreich",user)
redirect_to :back, notice: "Import Erfolgreich!"
else
#return errors
#format.html {render :index}
#format.json {render json: {status:"Fehler: ",message: "Dateiformat ist nicht erlaubt!"}}
redirect_to :back, notice: "Fehler"
end
#rescue
#redirect_to root_path, notice: "Invalid CSV file format."
end
end
end
现在我的模型课来了:
class FileUploadInfo < ActiveRecord::Base
require 'csv'
def initialize(file)
@file = file
end
def read_save_csv(file)
CSV.foreach(file.path, :headers => true) do |row|
file_hash = row.to_hash
end
return true
end
def import_file(file,time,status,user)
end
end
我被困在 import_file 功能上,需要一些建议。提前致谢!
解决方案
您可以初始化模型并使用 create 方法:您可以初始化模型并使用 save 方法:
file = FileUploadInfo.new
file.filename = filename
file.importdate = importdate
file.status = status
file.username = username
if file.save
// File saved succesfully
end
推荐阅读
- python - Django表单:如何设置字段的初始值,它当前包含在数据库中的值
- mysql - 通过特定的自定义字段订购 WP 查询,不起作用
- python - 使用 auto_arima(SARIMAX) 和傅里叶项预测具有多个季节性的时间序列
- html - 如何使 div 的大小与其父 div 大小相同
- java - Tomcat 从 ps -ef 对环境变量保密
- cockroachdb - 关闭 cockroachdb 单节点集群中的时间序列数据
- javascript - 为什么在循环一个空数组后在 angular12 中出现“无法编译错误”?
- powerbi - PowerBI:地图可视化未识别巴西“帕拉”州
- razor - 发布后是否可以在 MVC5 网站页脚中显示版本号?
- symfony - 带有 GetSetMethodNormalizer 的 Symfony 序列化程序返回一个空数组而不是日期