Ruby on Rails MVC - PullRequest
       4

Ruby on Rails MVC

0 голосов
/ 11 июня 2018

Я работаю над приложением на основе 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

This is my Table in Database

This is my user Table

Я застрял в функции import_file и нуждаюсь в некоторых советах здесь.Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 12 июня 2018

Спасибо за помощь.Я нашел обходной путь, и ниже мой модифицированный контроллер, и он работает довольно хорошо.

  class ImportCsvController < ApplicationController
  before_action :require_user
  before_action :require_admin

  def index
      # get the last 5 import history for dashboard
      @Fileimport = FileUploadInfo.order('updated_at DESC').limit(5)
  end

  # Import CSV file
  def import_csv_datei
    begin
        user=current_user.user_name
        time = Time.now
        status= "OK"
        filepath = params[:file]
        @file = FileUploadInfo.new
        @file.filename = filepath.original_filename
        @file.importdate = time.to_formatted_s(time)
        @file.status = status
        @file.username = user
        if @file.save
            #Import Successful
            #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
0 голосов
/ 11 июня 2018

Вы можете просто инициализировать вашу модель и использовать метод create: Вы можете просто инициализировать вашу модель и использовать метод save:

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

if file.save
   // File saved succesfully
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...