Reputation: 147
I've got a theoretical question about mailer in Rails. I've heard a pair of times that passing resources directly to mailer is not considerated as good practice. And that is its better simply pass an id to load the object. For example exactly this thing is said in the accepted answer in this question: Rails: Absolutely stumped with delayed_job. Not receiving arguments anywhere
But if it is so, what are the reasons of this prohibition? I can not treat linked question as an exhaustive explanation. Thank you for your suggestions.
Upvotes: 5
Views: 1490
Reputation: 6750
The "Rails Way" is for emails to be delivered later by a background job. That requires saving and restoring (serializing and deserializing) the arguments you pass to the job worker. If an object doesn't have a way to be serialized, then you'll have trouble.
If you are using deliver_later
with Active Job, passing a persisted ActiveRecord resource is automatically serialized to a GlobalId for you. You can also pass any of the supported types for arguments, or define a serializer for your object.
As of Rails 7.1, Active Job's supported types for serialization include:
String
Integer
Float
NilClass
TrueClass
FalseClass
BigDecimal
Symbol
Date
Time
DateTime
ActiveSupport::TimeWithZone
ActiveSupport::Duration
Hash
ActiveSupport::HashWithIndifferentAccess
Array
Range
GlobalID::Identification
instancesUpvotes: 0
Reputation: 1776
Reason is simple: it's more than 0% probability that your object will be changed between the time you're ordered to send mail and real mailer code execution. Imagine that object you're using will be deleted in process but since you don't have loaded your object at the execution time it'll try to use instance of object that's not exist anymore. I guess now you understand the problem.
Upvotes: 6