From 14942c20d7ff56599f918b5c277425bc902bdc62 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 16 Jun 2025 10:28:18 -0500 Subject: [PATCH] Add Provide Fake Form Helper To Controllers as a Rails TIL --- README.md | 3 +- ...provide-fake-form-helper-to-controllers.md | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 rails/provide-fake-form-helper-to-controllers.md diff --git a/README.md b/README.md index 84cb57d..7dc9d5f 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1646 TILs and counting..._ +_1647 TILs and counting..._ See some of the other learning resources I work on: - [Get Started with Vimium](https://egghead.io/courses/get-started-with-vimium~3t5f7) @@ -1099,6 +1099,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Prefer select_all Over execute For Read Queries](rails/prefer-select-all-over-execute-for-read-queries.md) - [Pretend Generations](rails/pretend-generations.md) - [Prevent Writes With A Sandboxed Rails Console](rails/prevent-writes-with-a-sandboxed-rails-console.md) +- [Provide Fake Form Helper To Controllers](rails/provide-fake-form-helper-to-controllers.md) - [Query A Single Value From The Database](rails/query-a-single-value-from-the-database.md) - [Read In Environment-Specific Config Values](rails/read-in-environment-specific-config-values.md) - [Read-Only Models](rails/read-only-models.md) diff --git a/rails/provide-fake-form-helper-to-controllers.md b/rails/provide-fake-form-helper-to-controllers.md new file mode 100644 index 0000000..43eda30 --- /dev/null +++ b/rails/provide-fake-form-helper-to-controllers.md @@ -0,0 +1,40 @@ +# 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](https://api.rubyonrails.org/v6.1.0/classes/ActionView/Helpers/FormBuilder.html) +object. + +One way to get around this that I've borrowed from [Justin +Searls](https://justin.searls.co/posts/instantiate-a-custom-rails-formbuilder-without-using-form_with/) +is with a `FauxFormHelper`. + +```ruby +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.