【问题标题】:Rails4 activemodel validations on concernsRails4 activemodel 对关注点的验证
【发布时间】:2013-09-30 18:37:36
【问题描述】:

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

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

这是正确的方法吗?

【问题讨论】:

  • first_namelast_name 等是实例方法,而不是类方法。您可能希望为 CSV.foreach 循环的每次迭代创建一个新的 Payslip 对象。
  • 如果我确实创建了一个新的 Payslip 对象,它会根据我上面的 Payslip 模型进行验证吗?

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我现在已将名称更改为 supperannuation,但错误不会从验证中抛出。任何想法为什么?
  • 我需要查看您的数据。您只是在验证是否包含。我不知道你期待什么错误。
猜你喜欢
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多