0

I've got below code in my model which I want to use for validation:

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

I have CSV import from the form and this gets passed over to 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

I've added Payslip.first_name etc in an attempt to validate and throw an error if not validated.

Is this the right approach?

Passionate Engineer
  • 10,034
  • 26
  • 96
  • 168

1 Answers1

0

Here's a rough suggestion on how I would handle the problem you're trying to solve. Feel free to comment if this isn't what you're looking for:

    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

Also, super is a reserved keyword, so I would suggest possibly not using it if you an avoid it.

Farley Knight
  • 1,795
  • 1
  • 13
  • 17