In Rails Action Mailer, how does OrderMailer.with(order: order).confirmation work, and what must its params hold for deliver_later?
answer
- with returns a proxy, not a mailer
- params readable in callbacks and defaults
- params travel in the job as params:
- Global ID for records
- ActiveJob::SerializationError at enqueue
basics
~20 swith(params) returns a proxy whose action calls build a parameterized delivery; inside the mailer, params is readable in actions, before_action callbacks and default lambdas. deliver_later passes that hash to the job, so every value must be Active Job serializable.
solid answer
~40 s`OrderMailer.with(order: order)` returns an `ActionMailer::Parameterized::Mailer` proxy; calling `.confirmation` on it builds a parameterized `MessageDelivery`. When the mailer runs, `params[:order]` is available everywhere: in the action, in `before_action` callbacks that set shared instance variables, and in `default` lambdas such as `default to: -> { @order.email }`. With `deliver_later`, the hash goes into `MailDeliveryJob` as its `params:` argument, and the worker calls `OrderMailer.with(params)` again. So every value must be something Active Job can serialize: an Active Record model (sent as a Global ID), strings, symbols, numbers, times, arrays and hashes of those. A plain Ruby object raises `ActiveJob::SerializationError` when the job is enqueued; a record deleted before the job runs raises `ActiveJob::DeserializationError`, which the mailer can handle with `rescue_from`.
code
ruby · 10 linesclass OrderMailer < ApplicationMailer
before_action { @order = params.fetch(:order) }
default to: -> { @order.email }
def confirmation
mail subject: "Order ##{@order.number} confirmed"
end
end
OrderMailer.with(order: order).confirmation.deliver_latergo deeper
Recognise OrderMailer.with(order: order).confirmation and know that params[:order] is how the mailer reads the value.
Explain the proxy, when params is assigned, and why before_action and default lambdas can use it to remove repeated setup.
Treat params as job arguments: keep them serializable, render snapshots explicitly, and handle DeserializationError with rescue_from on the mailer.
Set a convention for mailer inputs across teams, records or ids plus explicit snapshot values, so emails stay correct when they are delivered minutes later.
## Two ways to feed a mailer A mailer action can take **positional arguments**, `OrderMailer.confirmation(order)`, or read **params** set with `with`, `OrderMailer.with(order: order).confirmation`. Both send the same email; params pay off when several actions of one mailer share setup. A furniture store's `OrderMailer` might have `confirmation`, `shipped` and `delivery_scheduled`, and all three need `@order`, the customer and the same `to:` header. ## What `with` actually returns - `OrderMailer.with(order: order)` returns an `ActionMailer::Parameterized::Mailer`, a small proxy that remembers the class and the hash. - Calling an action on it, `.confirmation`, builds an `ActionMailer::Parameterized::MessageDelivery`. Calling something that is not an action of the mailer raises `NoMethodError` as usual. - When the delivery is processed, Rails creates the mailer, assigns `params` and only then runs the action, so the hash is present before any callback fires. - Without `with`, `params` is simply an empty hash. ## Where `params` is readable ```ruby class OrderMailer < ApplicationMailer before_action { @order = params[:order] } default to: -> { @order.email } def confirmation mail subject: "Order ##{@order.number} confirmed" end def shipped mail subject: "Order ##{@order.number} has shipped" end end ``` 1. The `before_action` runs first and sets `@order` from `params`. 2. The `default` lambda is evaluated on the mailer instance when `mail` merges its headers, so it sees `@order`. 3. Each action is now a one-liner that only sets what differs. This is the pattern the `Parameterized` module documents: shared instance-variable setup and common headers move out of every action. ## What happens with `deliver_later` `deliver_later` on a parameterized delivery enqueues `ActionMailer::MailDeliveryJob` with the mailer name, the action name, the delivery method and **`params:` holding your hash**, next to `args:` for any positional arguments. In the worker, the job calls `mailer.constantize.with(params)` and then the action. That round-trip through the queue is where people get caught: | Value in params | Result | |---|---| | `order` (an Active Record model) | serialized as a Global ID and reloaded in the worker | | `"A-1042"`, `:express`, `3`, `Time.current` | handled by Active Job's built-in serializers | | an app object such as `ReceiptPdf.new(order)` | `ActiveJob::SerializationError` ("Unsupported argument type") at enqueue | | an order destroyed before the job runs | `ActiveJob::DeserializationError` in the worker | Two practical rules follow: - **Pass records or plain values, and build heavy objects inside the mailer.** Generate the receipt PDF in the action from `@order`, not before enqueueing. - **Expect the record to change.** The worker reloads the order, so it renders the state at send time; pass a value explicitly if the email must show a snapshot, such as the price paid. ## Handling a record that vanished A `begin/rescue` inside the action cannot catch a deserialization failure, because it happens before the action runs. `MailDeliveryJob` rescues `StandardError` and hands the exception to the mailer class, which applies its `rescue_from` handlers, so the fix lives on the mailer: ```ruby class OrderMailer < ApplicationMailer rescue_from ActiveJob::DeserializationError do |error| Rails.logger.info("Skipped order email: #{error.message}") end end ``` If no handler matches, the exception is re-raised and the job fails like any other, subject to the queue backend's failure handling. ## Previews use the same entry point A preview can call `OrderMailer.with(order: Order.last).confirmation`, so the preview exercises exactly the code path production uses, callbacks and defaults included. ## Mistakes interviewers listen for - **Treating `params` like a controller's.** Mailer `params` is a plain hash you passed to `with`; it has nothing to do with the HTTP request and needs no `expect` or `permit`. - **Reading `params` in a class-level `default` without a lambda.** `default to: params[:order].email` is evaluated when the class loads, where there is no instance and no `params`; wrap it in `-> { ... }`. - **Mixing styles without need.** `OrderMailer.with(order: order).shipped(tracking_number)` is legal, since params and positional arguments both travel to the job, but one style per mailer keeps call sites predictable. - **Smuggling big blobs through params.** Strings are serializable, so a whole rendered PDF technically fits, but it bloats every queued job; pass the record and rebuild.
- When would you choose positional arguments over with?Positional arguments are simpler for a mailer with one action or unrelated actions, and they read like ordinary method calls. `with` wins when several actions share setup and headers, because the shared work moves into `before_action` and `default` lambdas that read `params`. Both serialize through the same job, so the serialization rules are identical.
- Why does a begin/rescue inside the action not catch a deleted order?The order is deserialized from its Global ID when the job starts, before the mailer action runs, so the exception is raised outside the method body. `MailDeliveryJob` passes it to the mailer class, where only a `rescue_from ActiveJob::DeserializationError` handler can deal with it.
- params in a mailer is the HTTP request's params, as in a controller.
- params is readable in the action but not in before_action callbacks.
- Any Ruby object can go into with for deliver_later, since jobs marshal arguments.
- A begin/rescue in the action catches a record deleted before delivery.
- Add retry_on to the mailer class to recover from a deleted record.