ActiveRecord transaction e-mails
I'm running a lib at my rails 3 app that performs several inserts and updates on different models. It's like importing a CSV shopping list file which may be with errors that abort the import function.
So I have something like this:
begin
ActiveRecord::Base.transaction do
@csv.each_with_index do |row, line_number|
begin
shopping_list_importer.import(row)
rescue Exception => e
invalid_objects << {:message => e.message, :line_number => line_number+2}
end
end
raise ActiveRecord::StatementInvalid if invalid_objects.present?
end
rescue ActiveRecord::StatementInvalid
end
My problem is that when a new shopping list item is created it sends an e-mail for the user. And when occurs some error the e-mail was already sended and the transaction doesn't block that. It's OK I understand why that occurs, and I should send the e-mails after the import, but my question is 开发者_JS百科that is there a more simple way to do this and keep using transaction block?
Thanks in advance, Andre.
What actually triggers email sends? If you keep that in a callback like after_save
it will not send any emails if object wasn't properly saved. Like:
after_save :send_notification
def send_notification
UserNotifier.something.deliver
end
I just found this: https://github.com/grosser/ar_after_transaction
It seems like it should solve this kind of problem elegantly.
精彩评论