ruby-on-railsruby

Rails form_with-helper: What is a :scope?


I'm currently reading the Ruby on Raily API-documentation. Specific the part about the form_with helper: https://api.rubyonrails.org/v5.1.7/classes/ActionView/Helpers/FormHelper.html#method-i-form_with

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

I don't understand what a "scope" is, within the context.

Can someone explain, what it means?


Solution

  • As the example in the docs shows, with the following code:

    <%= form_with scope: :post, url: posts_path do |form| %>
      <%= form.text_field :title %>
    <% end %>
    

    You will have the following HTML rendered:

    <form action="/posts" method="post" data-remote="true">
      <input type="text" name="post[title]">
    </form>
    

    Note the name attribute on an input: it is post[title] instead of just title (compare it to the previous example in the docs).

    You may want to do this, for example, if in Rails controller it'd be more convenient for you to retrieve the value of the field as params[:post][:title] instead of simply params[:title]. If you have more fields defined under post scope then in the controller you'd have them in params[:post] variable (for example, params[:post][:author], params[:post][:content])