0

I'm working on a project and I have to import some Phones to my website. Each phone have an IMEI and a ref_number.

However, some of those Phonesare already in the DB, which make the request longer and lead to an application error on Heroku.

Here's my phones_controller.rb :

def import_xlsx
  if params[:xlsx].nil?
    render :import_phones
  else
    filepath = params[:xlsx].path
    xlsx = Roo::Spreadsheet.open(filepath)
    xlsx = Roo::Excelx.new(filepath)
    xlsx.default_sheet = xlsx.sheets.first
    csv = xlsx.to_csv
    csv_options = { col_sep: ',', headers: :first_row, quote_char: '"' }
    csv_new = CSV.new(csv)
    CSV.parse(csv, csv_options) do |row|
      p = Phone.new(imei: row[0], ref_number: row[1])
      p.imei.gsub(/\s+/, "")
      if p.valid?
        p.save!
      else
        flash[:alert] = "#{p.imei}"
      end
    end
  redirect_to phones_import_path, notice: 'Votre fichier à bien été envoyer'
end

end

So, is there a way to do that or maybe to make the request faster ?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Enner31
  • 193
  • 1
  • 13

1 Answers1

3

in the Phone model you could add a uniqueness validator like this:

validate :imei, uniqueness: true

so that, when you try to save the phone, it won't pass validations and won't be saved. In this case, it's a validator of duplicate fields.

More info on validators

Getu
  • 179
  • 2
  • 9