首页 > 解决方案 > 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 功能上,需要一些建议。提前致谢!

标签: ruby-on-railsjsonbootstrap-4

解决方案


您可以初始化模型并使用 create 方法:您可以初始化模型并使用 save 方法:

file = FileUploadInfo.new
file.filename = filename
file.importdate = importdate
file.status = status
file.username = username

if file.save
   // File saved succesfully
end

推荐阅读