首页 文章

将current_user id分配给导入学生列表

提问于
浏览
0

其实我正在尝试将Excel文件导入rails 5应用程序 .

导入时我收到错误, ActiveRecord::RecordInvalid (Validation failed: User must exist)

这是我的student.rb

class Student < ApplicationRecord

  belongs_to :user

  mount_uploader :image, ImageUploader


  def self.search(search)

    where (["student_name LIKE ? OR admission_no LIKE ?", "%#{search}%","%#{search}%"])  

  end

  def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      note = find_by_id(row["id"]) || new
      note.attributes = row.to_hash.slice(*row.to_hash.keys)
      note.save!
    end
  end

  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::CSV.new(file.path)
    when ".xls" then Roo::Excel.new(file.path)
    when ".xlsx" then Roo::Excelx.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end 
  end    

end

这是我的students_controller.rb

def import
    Student.import(params[:file])
    redirect_to admissions_path, success: "File was successfully imported."
end

def new
    @student = current_user.students.build
end

def create
    @student = current_user.students.build(student_params)

    respond_to do |format|
      if @student.save
        format.html { redirect_to admissions_url, success: 'Student record was successfully created.' }
        format.json { render :show, status: :created, location: @student }
      else
        format.html { render :new }
        format.json { render json: @student.errors, status: :unprocessable_entity }
      end
    end
 end

def student_params
      params.require(:student).permit(:admission_no, :student_name, :surname, :user_id)
    end
end

任何建议都是最受欢迎的 .

先感谢您 .

1 回答

  • 1

    由于模型没有直接访问 current_user ,我只是将它传递给你的 Student.import 方法:

    def import
      Student.import(params[:file], current_user)
      ...
    end
    

    然后在模型方法中,在创建新的_49146时使用用户(不确定是否要更新现有学生,但您也可以这样做) . 像这样的东西:

    def self.import(file, user)
      ...
      note = find_by_id(row["id"]) || new(user: user)
      ...
    end
    

相关问题