我是RoR的新手。
我需要处理数据后,我得到它从文件。我认为有两种方法。
应用程序有三个模型:
Data
Segment - belongs to data
Point - belongs to Segment
第一种方法是:
- 创建类(<对象)并定义与模型> 相同的字段
- 读取数据到对象(类在1.)
- 过程数据
- 上传数据到数据库
第二种方式是:
- 读取数据到DB
- 处理数据
- 数据库更新
这样我就有了另一个问题-如何在一个事务中更新一堆点?
你能帮我接近它吗?
更新:可能我应该在哈希数组中读取文件数据,处理它并上传到DB?
只要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的表单。
我喜欢这种方法,只要你有一个漂亮的界面来上传帖子。甚至可以定义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
到目前为止,在这一点上失败了什么