create object if object is failed before_save
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
精彩评论