针对关注点的Rails4 activemodel验证

时间:2013-09-30 18:37:36

标签: ruby-on-rails ruby validation ruby-on-rails-4 activemodel

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

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

这是正确的方法吗?

1 个答案:

答案 0 :(得分: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是一个保留关键字,所以如果你避免使用它,我建议你不要使用它。