开发者

create object if object is failed before_save

开发者 https://www.devze.com 2023-01-08 06:41 出处:网络
Model def before_save self.default_file_name = \"#{self.model_name.underscore}.csv\" if self.default_file_name.nil?

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.no开发者_Python百科w, :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??


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
0

精彩评论

暂无评论...
验证码 换一张
取 消