1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00
Files
til/rails/provide-fake-form-helper-to-controllers.md

1.1 KiB

Provide Fake Form Helper To Controllers

I'm rendering a partial from a turbo stream. The partial is meant to be rendered within a Rails form object because it contains an input element that needs to reference the form object. The problem is that from the controller that is streaming the partial, there is no FormBuilder object.

One way to get around this that I've borrowed from Justin Searls is with a FauxFormHelper.

module FauxFormHelper
  FauxFormObject = Struct.new do
    def errors
    end

    def method_missing(...)
    end

    def respond_to_missing?(...)
      true
    end
  end

  def faux_form
    @faux_form ||= ActionView::Helpers::FormBuilder.new(
      nil,
      FauxFormObject.new,
      self,
      {}
    )
  end
end

This module defines and exposes a faux_form object that controllers and views can access. Then my partial can recieve that form object as a parameter.