完整示例
以上传包含联系人信息的导入文件为例。您不需要存储此导入文件,只需处理并丢弃它。
路由
routes.rb
resources :contacts do
collection do
get 'import/new', to: :new_import
post :import, on: :collection
end
end
表单
views/contacts/new_import.html.erb
<%= form_for @contacts, url: import_contacts_path, html: { multipart: true } do |f| %>
<%= f.file_field :import_file %>
<% end %>
控制器
controllers/contacts_controller.rb
def new_import
end
def import
begin
Contact.import( params[:contacts][:import_file] )
flash[:success] = "<strong>Contacts Imported!</strong>"
redirect_to contacts_path
rescue => exception
flash[:error] = "There was a problem importing that contacts file.<br>
<strong>#{exception.message}</strong><br>"
redirect_to import_new_contacts_path
end
end
联系模型
models/contact.rb
def import import_file
File.foreach( import_file.path ).with_index do |line, index|
end
end