0

我的模型中有以下代码,我想用于验证:

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_nameetc 以尝试验证并在未验证时抛出错误。

这是正确的方法吗?

4

1 回答 1

0

这是关于我将如何处理您要解决的问题的粗略建议。如果这不是您要查找的内容,请随时发表评论:

    def extract_csv(csv_file, headers)
        results = []
        CSV.foreach(csv_file.path, {headers: false, :encoding => 'UTF-8'}) do |row|
            data = row.split(',')
            payslip = Payslip.create({
                first_name: data[0],
                last_name:  data[1],
                super:      data[2]
            })

            results.push(row) unless $. == headers.to_i
        end
        return results
    end

另外,super是一个保留关键字,所以如果你避免使用它,我建议不要使用它。

于 2013-09-30T18:48:16.763 回答