ruby-on-railsdeviseform-for

Migrating from `form_for` over to the new `form_with`


How would one go about converting from form_for over to form_with for the following:

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %>

I've looked through Rails' form_with documentation but haven't found any relevant examples.

Thanks!


Solution

  • form_with has the scope: option that changes input name prefixes, ids and the for attribute of labels. As far as I can tell it does the exact same thing as the as: option for form_for.

    :scope - The scope to prefix input field names with and thereby how the submitted parameters are grouped in controllers.

    # Adding a scope prefixes the input field names:
    <%= form_with scope: :post, url: posts_path do |form| %>
      <%= form.text_field :title %>
    <% end %>
    # =>
    <form action="/posts" method="post" data-remote="true">
      <input type="text" name="post[title]">
    </form>
    

    https://api.rubyonrails.org/v6.0.0/classes/ActionView/Helpers/FormHelper.html#method-i-form_with

    So the equivalent call is:

    <%= form_with(
          model: resource, 
          scope: resource_name, 
          url: password_path(resource_name), 
          method: :post
        ) do |f| %>