将文件上传到服务器并将路径存储在Ruby on Rails中的数据库中

我对ROR很新。 我有一项任务要完成:

这是模型:

class File::DataImport < ActiveRecord::Base attr_accessible :created_by, :file_name, :file_source, :updated_at, :updated_by end 

这是控制器:

 class Files::DataImportsController < ApplicationController def index end def new end end 

我的观点是indexnew

我想要一个字段来上传数据。 数据应存储在服务器中,并将文件路径保存到指定列file_name的数据库中。 该路径应默认为所有上传文件。

我被困在如何开始。 请帮助我找到解决方案,我将从中学习。

提前致谢。

分贝/迁移/ 20110711000004_create_files.rb

 class CreateFiles < ActiveRecord::Migration def change create_table :files do |t| t.string :name # If using MySQL, blobs default to 64k, so we have to give # an explicit size to extend them t.binary :data, :limit => 1.megabyte end end end 

应用程序/控制器/ upload_controller.rb

  class UploadController < ApplicationController def get @file = File.new end end 

应用程序/视图/上传/ get.html.erb

 <% form_for(:file, url: {action: 'save'}, html: {multipart: true}) do |form| %> Upload your file: <%= form.file_field("uploaded_file") %>
<%= submit_tag("Upload file") %> <% end %>

应用程序/模型/ file.rb

 class File < ActiveRecord::Base def uploaded_file=(file_field) self.name = base_part_of(file_field.original_filename) self.data = file_field.read end def base_part_of(file_name) File.basename(file_name).gsub(/[^\w._-]/, '') end end 

应用程序/控制器/ upload_controller.rb

 def save @file = File.new(params[:file]) if @file.save redirect_to(action: 'show', id: @file.id) else render(action: :get) end end 

应用程序/控制器/ upload_controller.rb

 def file @file = File.find(params[:id]) send_data(@File.data, filename: @File.name, disposition: "inline") end 

应用程序/控制器/ upload_controller.rb

 def show @file = File.find(params[:id]) end 

应用程序/视图/上传/ show.html.erb

 

<%= @file.name %>

您应该考虑使用已经可用的解决方案之一,如paperclip: https ://github.com/thoughtbot/paperclip或carrierwave: https ://github.com/jnicklas/carrierwave

除了Readmes之外,还有很好的教程:

http://railscasts.com/episodes/134-paperclip

http://railscasts.com/episodes/253-carrierwave-file-uploads

编辑:由于你想自己实现它,我建议在Github上检查上面的源代码并尝试理解他们的代码在做什么。 此外,我不打算自己实施,但如果你有理由,这可能会让你去…

您可能希望研究诸如carrierwave之类的解决方案。

Github页面提供了如何使用它的一个很好的解释,但这也是一个很好的指南。