Rails中为Excel导入添加年份参数并实现对应数据删除
解决方案
1. 修复控制器:获取年份并执行删除操作
你当前的create方法先调用删除逻辑,但此时还未初始化导入对象,无法获取年份参数。同时Rails 7要求必须使用强参数过滤请求字段,调整后的控制器代码如下:
class OvertimesImportsController < ApplicationController def new @overtimes_import = OvertimesImport.new end def create @overtimes_import = OvertimesImport.new(overtimes_import_params) # 验证年份存在后再删除对应旧数据 delete_old_overtimes(@overtimes_import.year) if @overtimes_import.year.present? respond_to do |format| if @overtimes_import.save format.html { redirect_to root_path, notice: "Overtimes successfully imported." } else format.html { render :new, status: :unprocessable_entity } end end end private # 根据传入年份删除旧数据 def delete_old_overtimes(year) Overtime.where(year: year).delete_all end # 强参数:允许file和year字段 def overtimes_import_params params.require(:overtimes_import).permit(:file, :year) end end
2. 给导入的加班记录赋值年份
在OvertimesImport模型的导入逻辑中,需要把用户提交的year赋值给每个生成的Overtime对象,确保年份存入数据库:
def load_imported_overtimes spreadsheet = open_spreadsheet header = spreadsheet.row(1) (2..spreadsheet.last_row).map do |i| row = Hash[[header, spreadsheet.row(i)].transpose] overtime = Overtime.new overtime.attributes = row.to_hash # 将导入对象的year属性赋值给加班记录 overtime.year = self.year overtime end end
3. 可选:添加年份合法性验证
为避免空年份或非法年份导入,可在OvertimesImport模型中添加验证规则:
class OvertimesImport include ActiveModel::Model require 'roo' attr_accessor :file, :year # 验证年份必填且为合法整数 validates :year, presence: true, numericality: { only_integer: true, greater_than: 2000 } validates :file, presence: true # ... 其余原有代码保持不变 ... end
内容的提问来源于stack exchange,提问作者balou7
相关产品推荐
相关产品推荐

