ScreenshotNeo

BlogHow-to

How to Make Rails View Helpers Work with render_to_string

Fix undefined Rails helpers in render_to_string by choosing the right controller declaration, helper_method, or renderer context.

By the ScreenshotNeo team30 September 20269 min read

How to Make Rails View Helpers Work with render_to_string

render_to_string returns rendered template output as a string. It does not change which methods a template can call. If a helper is undefined, fix the helper visibility or rendering context separately from the fact that the output is being returned instead of sent as the response.

For a custom view helper, declare the module on the controller:

class ReportsController < ApplicationController
  helper ReportsHelper
end

For a controller method that a view must call, expose that named method with helper_method:

class ApplicationController < ActionController::Base
  helper_method :current_user

  private

  def current_user
    # application-specific lookup
  end
end

Those are different mechanisms. A helper module supplies view presentation methods; helper_method makes a controller method available to templates. When rendering outside a normal action, also verify the controller renderer, view context, request state, and Rails version.

What render_to_string actually does

Rails documents render_to_string as taking the same options as render, while returning a string instead of sending a response to the browser. The method can render a template, partial, layout, or an explicit format. The returned value is ordinary Ruby text, so you can place it in an email, an API payload, a job result, a cache entry, or a later response.

class ReportsController < ApplicationController
  def preview
    @report = Report.find(params[:id])
    html = render_to_string(
      template: "reports/show",
      formats: [:html],
      layout: "reports"
    )

    render json: { html: html }
  end
end

The rendering call does not automatically make every controller method or helper module available. Rails builds a view context from the controller and its configuration. The template can call methods in that context, but method ownership matters.

Choose the mechanism that matches the method

What the template needs Use Example
Formatting or presentation methods in a module helper helper ReportsHelper
A specific method implemented by the controller helper_method helper_method :current_user
A helper from controller-side Ruby code The controller’s helpers proxy helpers.number_to_currency(total)
Rendering without an action A controller renderer and verified view context ApplicationController.renderer.render(...)

Do not use helper_method to expose an entire helper module. Do not assume that calling helpers from a controller changes the methods available inside a separately constructed renderer.

The controller and renderer build a view context before the template becomes a string.
The controller and renderer build a view context before the template becomes a string.

Declare a custom helper module

Put presentation logic in a helper module and attach it to the controller whose templates need it.

# app/helpers/reports_helper.rb
module ReportsHelper
  def report_status_badge(report)
    css = report.published? ? "badge badge-success" : "badge badge-muted"
    content_tag(:span, report.status.humanize, class: css)
  end
end

# app/controllers/reports_controller.rb
class ReportsController < ApplicationController
  helper ReportsHelper

  def show
    @report = Report.find(params[:id])
    @html = render_to_string(template: "reports/show")
  end
end

The template can now call report_status_badge(@report) because ReportsHelper is included in the view context created for this controller.

<article>
  <h1><%= @report.title %></h1>
  <%= report_status_badge(@report) %>
</article>

You can declare more than one module:

class ReportsController < ApplicationController
  helper ReportsHelper, ChartsHelper
end

For a one-off template, an inline helper block is also possible:

class ReportsController < ApplicationController
  helper do
    def compact_number(value)
      number_to_human(value, precision: 3)
    end
  end
end

Prefer named modules for reusable behavior. Inline declarations are harder to discover and test.

Expose a controller method with helper_method

Use helper_method when the method belongs to the controller but the template is intentionally allowed to call it. This is common for authentication state, navigation state, or a small piece of request-specific data.

class ApplicationController < ActionController::Base
  helper_method :current_user, :signed_in?

  private

  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  def signed_in?
    current_user.present?
  end
end

A template can then use:

<% if signed_in? %>
  <span>Signed in as <%= current_user.name %></span>
<% end %>

Expose only the methods that are part of the view contract. Keeping unrelated controller methods private reduces accidental coupling. The Rails API documents this declaration as the way to make named controller methods available to views: AbstractController helper class methods.

Render with the correct controller context

Inside an action, the normal controller instance supplies request state, assigns, formats, layouts, and helper configuration:

class ReportsController < ApplicationController
  helper ReportsHelper

  def export
    @report = Report.find(params[:id])
    render_to_string(
      template: "reports/show",
      layout: "reports",
      assigns: { exported_at: Time.current }
    )
  end
end

Outside an action, use a renderer associated with the controller class:

renderer = ReportsController.renderer.new(
  http_host: "example.test",
  https: true
)

html = renderer.render(
  template: "reports/show",
  assigns: { report: report },
  layout: "reports"
)

The exact behavior can depend on the controller class, included helpers, Rails version, and request-related state assumed by the helper. Check the Rails version in your lockfile and reproduce the same call path used by the application. Avoid manually instantiating ActionView::Base or globally including modules before you understand which context your renderer creates.

Rendering options that affect helper behavior

  • template: Selects a template such as reports/show.
  • partial: Renders a partial, usually with locals.
  • layout: Wraps the output in a layout or disables it with false.
  • formats: Sets the lookup format, for example [:html].
  • handlers: Selects a template handler when your application uses more than one.
  • locals: Supplies local variables to a partial.
  • assigns: Supplies instance variables when using a renderer.
  • status/content_type: Relevant when rendering a response; they do not alter helper inclusion.
html = renderer.render(
  partial: "reports/row",
  formats: [:html],
  locals: { report: report },
  layout: false
)

A missing local and an undefined helper look similar in a stack trace but have different fixes. A local must be passed in locals; a helper must be included in the view context or exposed with helper_method.

Rails configuration and version differences

Current Rails documentation describes all helpers as included by default in the documented behavior. Applications can set config.action_controller.include_all_helpers = false to restore older controller-specific inclusion behavior. Inspect the application’s environment configuration instead of assuming the default.

# config/application.rb or an environment file
config.action_controller.include_all_helpers = false

When that setting is false, explicitly declaring the module with helper ReportsHelper is especially important. Configuration is loaded at boot, so restart the relevant process after changing it.

Debugging checklist

  1. Read the exception and identify the missing method name.
  2. Search for its definition. Is it in a helper module, controller, concern, decorator, or model?
  3. If it is a helper module, add helper ModuleName to the controller that renders the template.
  4. If it is a controller method, add helper_method :method_name.
  5. If rendering through ApplicationController.renderer, switch to the actual controller class that owns the helper declaration.
  6. Check include_all_helpers and the Rails version in Gemfile.lock.
  7. Verify request assumptions such as session, current_user, url_options, host, protocol, locale, and time zone.
  8. Restart the process after changing helper files or configuration if code reloading is not active.

Common errors, causes, and fixes

Error or symptom Likely cause Fix
undefined method ... for #<...> in a template The module is not in the view context Declare it with helper ReportsHelper on the rendering controller.
A controller method works in an action but not in ERB The method was not exposed to views Add helper_method :method_name.
Works in a browser request but fails in a job The job uses a different renderer and has no request state Use the correct controller renderer and provide host, protocol, assigns, and any required context.
Helper works in one controller but not another Controller-specific inclusion or configuration differences Declare the module on the second controller or include a shared module in ApplicationController.
URL helper raises a host or protocol error No request URL options exist outside an action Configure renderer options such as http_host and https, or pass explicit URL options.
Helper sees a nil session or user There is no browser request/session in the renderer Pass the needed value as an assign or establish the request context deliberately.
Changing a helper has no effect Stale process, cache, or a different template path Restart the process, verify the template name, and inspect the rendered controller class.
Partial cannot find a local The local was not supplied Pass it with locals: { name: value }.

Performance and reliability considerations

Rendering to a string performs template lookup, helper execution, partial rendering, and often layout rendering. Keep expensive database queries out of helpers; load records in the controller or service and pass the result to the view. Avoid making a helper perform one query per row. If output is reused, cache the final fragment or the data needed to build it, while accounting for locale, permissions, and request-specific values.

ScreenshotNeo removes common overlays before capturing the page.
ScreenshotNeo removes common overlays before capturing the page.

For background jobs, make inputs explicit. A renderer has no browser session, current request, or implicit host unless you provide one. This makes jobs more predictable and avoids accidentally depending on thread-local request state. If a helper reads time, locale, or feature flags, set those values around the render and restore them afterward.

Rendering can raise template, helper, asset, missing-record, or URL-generation exceptions. Treat the returned string as successful only after the render call completes. Log the controller class, template, format, and key identifiers when diagnosing failures, while avoiding secrets and personal data.

Or skip the browser setup

If the next step is turning the rendered page into an image or PDF, ScreenshotNeo provides a single HTTP request instead of maintaining browser automation. Its API can capture PNG, JPEG, WebP, or PDF output, with options for full-page screenshots, selectors, waits, custom CSS and JavaScript, cookies, headers, device presets, dark mode, and more. See the ScreenshotNeo documentation for the complete parameter list.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

Create a free ScreenshotNeo account and try the API with 1,000 shots per month at no charge.

FAQ

Does render_to_string include all helpers?

It uses the helper configuration of the controller and view context doing the render. Explicitly declare custom modules when behavior depends on them, and check include_all_helpers for older or customized applications.

Should I use helper_method for a module?

No. Use helper ModuleName for a helper module. Use helper_method for individual controller methods.

Can I call a helper from controller code?

Use the controller’s helpers proxy for view helper behavior. That does not automatically change the methods available to a separately created renderer.

Why does the same template work in a request but fail in a job?

A job usually has no request, session, host, or controller instance. Render through the appropriate controller renderer and supply the assigns and request options the template requires.

Does render_to_string send an HTTP response?

No. It returns the rendered output as a string. Your code decides whether to return it, store it, embed it elsewhere, or render it later.

Primary references