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

时间:2018-12-09 09:23:35

标签: ruby ruby-on-rails-5.2

实际上,我正在尝试将Excel文件导入Rails 5应用程序。

导入时出现错误, ActiveRecord :: RecordInvalid(验证失败:用户必须存在)

这是我的学生。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 个答案:

答案 0 :(得分:1)

由于模型无法直接访问current_user,因此我将其传递给您的Student.import方法:

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

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

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