我的模型中有以下代码,我想用于验证:
class Payslip < ActiveRecord::Base
include ActiveModel::Validations
attr_accessor :first_name, :last_name, :annual_salary, :super, :payment_start_date
validates :annual_salary, :super, numericality: { only_integer: true },
presence: true
validates :super, inclusion: { in: 0..50 }
validates :first_name, :last_name, presence: true,
length: { maximum: 100 }
validates_date :payment_start_date
validates :payment_start_date, presence: true
end
我从表单导入了 CSV,这被传递给concern
:
module CSV_Manager
extend ActiveSupport::Concern
class << self
def extract_csv(csv_file, headers)
results = []
CSV.foreach(csv_file.path, {headers: false, :encoding => 'UTF-8'}) do |row|
data = row.split(',')
Payslip.first_name = data[0]
Payslip.last_name = data[1]
Payslip.super = data[2]
results.push(row) unless $. == headers.to_i
end
return results
end
def prepare_csv(rows, headers)
csv_file = CSV.generate do |csv|
csv << headers
rows.map { |row| csv << row }
end
return csv_file
end
end
end
我添加了Payslip.first_name
etc 以尝试验证并在未验证时抛出错误。
这是正确的方法吗?