如果对象在before_save中失败,则创建对象

时间:2010-07-20 15:15:15

标签: ruby-on-rails ruby callback

模型

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

在这段代码中我想在我的数据库中创建一个新的日志行,如果self.errors包含错误但我无法存储,因为对象无法保存而不是回滚事务。

我怎么处理这个?

1 个答案:

答案 0 :(得分:0)

您可以在保存失败时创建日志。

# 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