26 Sep
Rails form_with
This week I want to tell you about the form_with Rails helper. It was introduced in Rails 5.1, and the goal of this helper was to unify the form_for and the form_tag helpers. form_for requires a model instance or a scope and puts the attributes into a hash, so usually when you needed a form in the past where you didn’t want to put them scoped into a hash, you used form_tag.
Since the introduction of form_with, we can use the same helper for both use cases and specify a model, a scope, or just a URL. If you specify a model instance, it infers the URL and the scope. If it is a persisted one, it will generate an update form with the appropriate URL and HTTP method.
![](https://pombomailer.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MTcxLCJwdXIiOiJibG9iX2lkIn19--e810f810a6cd2ff59ac1bbcae56debae5f2d6ce6/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJwbmciLCJyZXNpemVfdG9fbGltaXQiOlsxMDI0LDc2OF19LCJwdXIiOiJ2YXJpYXRpb24ifX0=--cefc62acd607acb36c209b04aa5893ccc86cdf29/carbon%20(13).png)
If you set a scope it will put all fields into a hash under the scope and if you only set a URL, the fields won’t be put into a hash:
![](https://pombomailer.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MTcyLCJwdXIiOiJibG9iX2lkIn19--76485944992ae70b6a1929efa02546c6bb200854/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJwbmciLCJyZXNpemVfdG9fbGltaXQiOlsxMDI0LDc2OF19LCJwdXIiOiJ2YXJpYXRpb24ifX0=--cefc62acd607acb36c209b04aa5893ccc86cdf29/carbon%20(14).png)
You can also mix the above options and use a model with a custom scope and/or URL.
A few important things to remember about form_with:
- if you call form_with without a block, it generates just an opening form tag
- it has a local option, which is false by default, meaning it generates form tags submitted as a remote form with Rails UJS. This local option doesn’t control turbo though in Rails 7, if you want to disable that, you need to set the data-turbo attribute to false.
That’s it for the week. Until next time!