views:

52

answers:

1

Model

def before_save
  self.default_file_name = "#{self.model_name.underscore}.csv" if self.default_file_name.nil?
  self.default_directory_name = "public/uploads" if self.default_directory_name.nil?
  verify_methods
  verify_record
end

def verify_methods
  self.errors.add_to_base(_("Invalid row instance method.")) \
  if !self.each_row_instance_method.nil? && !self.model_name.constantize.instance_methods.include?(self.each_row_instance_method)

  self.errors.add_to_base(_("Invalid complete class method.")) \
  if !self.on_complete_class_method.nil? && !self.model_name.constantize.methods.include?(self.on_complete_class_method)

  return false if self.errors.count > 0
end

def verify_record
  self.csv_columns.each do |csv_column|
    self.errors.add_to_base(_("Invalid column name #{csv_column.column_name}.")) \
    unless self.model_name.constantize.column_names.include?(csv_column.column_name)
  end

  Log.create! :start_time => Time.now, :finish_time => Time.now,:message => self.errors.full_messages.to_s, :success => "N" if self.errors.count > 0

  return false if self.errors.count > 0
end

In this code i want to create a new log row in my database if self.errors contains a errors but i was not able to store that because on object failed to save than it will rollback transaction.

How may i handle this??

A: 

You can just create the log when the save fails.

# on controller
if model.save
  # do something
else
  model.log!
end


# on the model
def log!
  Log.create! :start_time => Time.now, :finish_time => Time.now, :message => self.errors.full_messages.to_s, :success => "N" if self.errors.count > 0
end
htanata
But i can't create log in before_save. Can i except that line from transaction?? Is there anyway of nested transaction or something else with that i can handle it inside before_save??
krunal shah
I tried to put the Log creation in validation callback but it also gets rolled back. Seems like the easiest way to do it is to do an `if else` when calling `save`. Other technique that may work is by creating a separate database connection for the Log model so the transaction doesn't apply, but I'm not sure.
htanata