已经跟随RailsCast上导入CSV( http://railscasts.com/episodes/396-importing-csv-and-excel ),我想验证所上传的文件是一个CSV文件。
我已经使用了宝石csv_validator
这样做,因为这里记录https://github.com/mattfordham/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