2016-05-18 65 views
2

下面的函数工作正常但是,如果任何记录包含非UTF-8字符,则会给出500错误。如何在Ruby on Rails中创建批量操作事务

我可以在这里使用事务进行批量操作,以便保存所有记录或者不保存所有记录吗?

我已经尝试使用各种编码修复问题,如在stackoverflow中提到的,但这并不起作用。

def convert_save(model_name, csv_data, field_name=nil) 
     target_model = model_name.classify.constantize 
     csv_file = csv_data.read 
     row_headers={} 
     counter=0; 
     all_recs=[]; 
     #Thread.new do 
       CSV.parse(csv_file) do |row| 
        if counter==0 
         temp=row 
         row_headers = Hash[temp.map.with_index.to_a] 
         counter +=1 
         next 
        end 
         #start fetch row and put into active record object 
         unless row[row_headers["name"]].nil? 
          temp={} 
          temp_time={} 
          for name in [:business_type_id, :user_id, :name, :country_id, :latitude, :longitude, :free_shipping] 
           temp[name] = row[row_headers[name.to_s]] 
          end 
          for name in [:homepage, :telephone, :email, :address, :facebook, :twitter, :google, :instagram, :pinterest, :ship_details] 
           temp[name] = row[row_headers[name.to_s]] ||= "" 
          end 
          for name in [:category_ids, :style_ids, :filter_ids, :shipping_country_ids] 
           temp[name] = row[row_headers[name.to_s]].try(:split, ",") unless row_headers[name.to_s].nil? 
          end 
          for name in [:monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday, :public_holiday] 
           temp_time[name.to_s] = row[row_headers[name.to_s]] ||= "" 
          end 
          temp_time["appointment_only"] = row[row_headers["appointment_only"]] 
          temp["business_timing_attributes"] = temp_time 
          all_recs.push(temp) 
         end 
       end 
       Business.create(all_recs) 
       ActiveRecord::Base.connection.close 
     end 
    #end 
    end 
+0

这似乎是你问交易以及编码问题。您应该一次尝试提出一个问题。 –

+0

交易的主要动机是避免编码错误。如果由于编码部分记录保存而出现任何问题,则会造成问题。直到现在我还没有找到更好的编码解决方案。 –

+0

这看起来像[XY问题](http://xyproblem.info/)。如果您遇到编码错误和其他SO问题并未帮助您解决问题,则应发布描述问题的问题,其中包括您收到的确切错误消息。 –

回答

1

您可以在交易中包装您的create方法。如果任何INSERT失败,整个操作将被回滚:

Business.transaction do 
    Business.create!(all_recs) 
end 

注意,为了让事务回滚一个ActiveRecord错误发生的查询结果。因此,您必须在此处使用create!而不是create以确保为无效数据抛出异常。

+0

感谢它的工作,但如何创建和创建!在这里工作 –

+0

'create'将会运行,但自从'transaction'中的查询开始运行后,它不会为所有用户回滚INSERTS。 –

相关问题