Search code examples
ruby-on-railssandbox

rails3 working in sandbox environment


Is there any way of switching on/off sanbox environment for activerecord in rails?

I'm developing a rails application. I have a case where I need to load data from xls and csv files. Each row of the table is inserted to database separately. When some mistake is found in any row, I need to cancel all previously inserted rows and show an error message. The perfect solution would be to "switch on" sandbox environment for activerecord, insert data, then if every line is correct make the the previous insertions "happen", and then "switch off" the sandbox environment. Is this possible in rails?


Solution

  • It depends on what time do those insert take. If you don't mind locking the database for that time, you can use transactions:

    MyModel.transaction do
       objects.each do |object|
          object.attributes = values
          object.save!
       end
    end
    

    The transaction rescues all exceptions by itself and if any occurs, all previous saves are rolled back.