如何在存储到DB之前从文件上传后处理数据?

时间:2014-06-21 15:23:37

标签: ruby-on-rails

我是RoR的新人。

我需要在从文件中获取数据后处理数据。 我认为有两种方法可以做到。

应用程序有3个模型:

Data
Segment - belongs to data
Point - belongs to Segment

第一种方式是:

  1. 创建类(< Object)并定义相同的字段,如模型
  2. 将数据读取到对象(1中的类)。
  3. 处理数据
  4. 将数据上传到数据库
  5. 通过这种方式,我有一个问题 - 定义类的最佳位置是什么? Model,/ lib等?

    第二种方式是:

    1. 将数据读取到DB
    2. 处理数据
    3. DB中的更新
    4. 通过这种方式,我还有另外一个问题 - 如何在一次交易中更新一堆积分?

      你能帮我解决一下吗?

      更新: 可能是我应该读取散列数组中的文件数据,处理它并上传到DB?

1 个答案:

答案 0 :(得分:2)

只要Rails被设计为Web服务器,这将是我最好的方法:

routes.rb
  post '/uploads/log/', to: 'logs#create'

uploads_controller.rb

  def create
    @upload = Upload.new(parsed_upload_file) #define a method to parse the filetype
    if @upload.save
      #actions after save like show the parsed result or whatever
    else
      #display errors like format issues or actions to perform
    end
  end

uploads.rb #model
class Upload << ActiveRecord::Base
  attr_accessor #if you need attributes not defined in the db but in the file
  before_create :pre_process_data


  private
  def pre_process_data
     #actions to preprocess data
  end
end

使用上传字段或网址定义表单。

我喜欢这种方法,只要你有一个很好的界面上传帖子。即使你可以定义url来获取它们,或者cron也可以使用该文件对该url执行自动请求。

对于另一个问题,我不喜欢交易,只要你可能需要知道哪一个失败了。我宁愿建议这样做:

def bunch_update
   @invalid_points = []
   points_array.each do |point|
     new_point = Point.new(point)
     @invalid_points << new_point unless new_point.valid?
   end
   points_array.each {|point| point.save} if @invalid_points.empty?
end

通过这个你可以在视图中使用:

@invalid_points.each do |point|
  point.errors.full_messages
end

到目前为止,在这一点上失败了。

相关问题