Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Is it better to send email notifications from a model or a controller?

Assume mailings are sent of to be processed later (i.e. through starling or delayed_job).

What I want to know is its a better practice to send email notifications from ActiveControllers or ActiveRecords?

I guess its useful to put it in the controller since you might want to control whether an email SHOULD be sent or not (i.e. after a model saves some other criteria might be important) but the idea that there is ONE place (the model) that the email gets sent from if its processed from the model after a save (create or update etc) is also useful.

Have anyone of you had this dilemma? Which did you choose and why? Did you do something completely different?

like image 633
aarona Avatar asked Dec 17 '22 21:12

aarona


2 Answers

I personally like having everything grouped together in ActiveRecord. However, for email sending specifically, I always do it from the controller. Just imagine that you are running unit tests, or you change some record from the console. Those are two situations I come up against where I do not want emails to be sent.

like image 140
Faisal Avatar answered Dec 19 '22 09:12

Faisal


IMHO, rails is a flexible framework and, whichever way you start, you can always switch from model to controller and back with almost zero effort. In other words, it's just not a problem worth spending 2 hours on.

But the important thing is that you have all sending code in one place (usually in a subclass of ActionMailer::Base). This way, changing place you send email from is just moving one line of code.

like image 42
Nikita Rybak Avatar answered Dec 19 '22 09:12

Nikita Rybak