2016-08-09 2 views
1

CSV(http://railscasts.com/episodes/396-importing-csv-and-excel)をインポートする際にRailsCastを実行した後、アップロードするファイルがCSVファイルであることを検証しようとしています。Ruby on Rails:CSVファイルを検証する

ここ https://github.com/mattfordham/csv_validator

を文書化し、ので、私のモデルは次のようになりますように私には、そうするために宝石csv_validatorを使用している

class Contact < ActiveRecord::Base 
    belongs_to :user 

    attr_accessor :my_csv_file 
    validates :my_csv_file, :csv => true 

    def self.to_csv(options = {}) 
    CSV.generate(options) do |csv| 
     csv << column_names 
     all.each do |contact| 
      csv << contact.attributes.values_at(*column_names) 
     end 
    end 
    end 
    def self.import(file, user) 
    allowed_attributes = ["firstname","surname","email","user_id","created_at","updated_at", "title"] 
    CSV.foreach(file.path, headers: true) do |row| 
     contact = find_by_email_and_user_id(row["email"], user) || new 
     contact.user_id = user 
     contact.attributes = row.to_hash.select { |k,v| allowed_attributes.include? k } 
     contact.save! 
    end 
    end 
end 

しかし、私のシステムはまだ私が非CSVをインポートするために選択することができますファイル(.xlsなど)に変換され、結果のエラー:invalid byte sequence in UTF-8が表示されます。

誰かが理由と解決方法を教えてください。

私はRailsの4.2.6を使用していますので、予めご了承ください

+0

インポートする前にファイルの拡張子を確認することができます: 'file.path.split( '。')。last.to_s.downcase == 'csv'' – MrYoshiji

+0

@MrYoshijiご意見ありがとうございます。この宝石が私にできることを許可するべきである特定の列のデータを検証するために –

+0

この宝石は列のデータを取り出すことを可能にし、ロジックを「データを検証する」ようにするあなたの部分です。カラム。私はあなたがどこで始めるべきかについていくつかのヒントを望むならば、答えを掲示することができます – MrYoshiji

答えて

1
あなたがのは ContactCsvRowValidatorを言わせて、新しいクラスを作成することができ

class ContactCsvRowValidator 

    def initialize(row) 
    @row = row.with_indifferent_access # allows you to use either row[:a] and row['a'] 
    @errors = [] 
    end 

    def validate_fields 
    if @row['firstname'].blank? 
     @errors << 'Firstname cannot be empty' 
    end 

    # etc. 
    end 

    def errors 
    @errors.join('. ') 
    end 
end 

をし、このようにそれを使用します。

# contact.rb 
def self.import(file, user) 
    allowed_attributes = ["firstname","surname","email","user_id","created_at","updated_at", "title"] 
    if file.path.split('.').last.to_s.downcase != 'csv' 
    some_method_which_handle_the_fact_the_file_is_not_csv! 
    end 
    CSV.foreach(file.path, headers: true) do |row| 
    row_validator = ContactCsvRowValidator.new(row) 
    errors = row_validator.errors 
    if errors.present? 
     some_method_which_handle_the_fact_this_row_is_not_valid!(row) 
     return 
    end 

    # other logic 
    end 
end 

このパターンは、あなたのニーズに合わせて簡単に変更できます。たとえば、複数の異なるモデルにインポートする必要がある場合は、validate_fields,initializeerrorsなどの基本的なメソッドを提供するCsvRowValidatorベースを作成できます。次に、独自の検証を実装して、必要な各モデルに対してこのCsvRowValidatorを継承するクラスを作成できます。

関連する問題