diff --git a/README.md b/README.md index b103404..7cba661 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). -_1599 TILs and counting..._ +_1600 TILs and counting..._ See some of the other learning resources I work on: - [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators) @@ -1004,6 +1004,7 @@ See some of the other learning resources I work on: - [Different Ways To Add A Foreign Key Reference](rails/different-ways-to-add-a-foreign-key-reference.md) - [Disambiguate Where In A Joined Relation](rails/disambiguate-where-in-a-joined-relation.md) - [Empty find_by Returns First Record](rails/empty-find-by-returns-first-record.md) +- [Enforce Locals Passed To A Partial](rails/enforce-locals-passed-to-a-partial.md) - [Ensure A Rake Task Cannot Write Data](rails/ensure-a-rake-task-cannot-write-data.md) - [Ensure Migrations Use The Latest Schema](rails/ensure-migrations-use-the-latest-schema.md) - [Ensure Record Saved With after_commit Callback](rails/ensure-record-saved-with-after-commit-callback.md) diff --git a/rails/enforce-locals-passed-to-a-partial.md b/rails/enforce-locals-passed-to-a-partial.md new file mode 100644 index 0000000..52fbb44 --- /dev/null +++ b/rails/enforce-locals-passed-to-a-partial.md @@ -0,0 +1,42 @@ +# Enforce Locals Passed To A Partial + +I have a big form partial (`_form.html.erb`) that is rendered by several +different _new_ and _edit_ views. It's hard to tell at a glance, but the +partial requires that `blogmark` and `cancel_path` are included as locals when +it is rendered. + +As of [Rails 7.1](https://github.com/rails/rails/pull/45602), we now have a +built-in way to enforce locals passed to a partial. We can add a magic comment +at the top of the partial that specifies the locals: + +```ruby +<%# locals: (blogmark:, cancel_path:) -%> +<%= form_with(model: blogmark, local: true, class: "w-full max-w-3xl mb-8") do |form| %> + <% ... %> +<% end %> +``` + +This particular ERB magic comment declares that +[`blogmark`](https://still.visualmode.dev/blogmarks) and `cancel_path` are +required locals. + +So, what happens if I have a `new.html.erb` view that looks like this: + +```ruby +