Search code examples
ruby-on-railsrubydata-binding

Binding a Form to an Object: What means "scoped" in such a context?


From the Ruby on Rails-guides:

"Binding a Form to an Object

The :model argument of form_with allows us to bind the form builder object to a model object. This means that the form will be scoped to that model object, and the form's fields will be populated with values from that model object."

Source: Article

What means "scoped" in the described context?

I know "scope" as an area, in which a specific variable/constants is visible, respectively accessible. I'm not sure, what is means here.


Solution

  • You need read below text of that guides

    The following form:

    <%= form_with model: @article do |form| %>
     <%= form.text_field :title %>
     <%= form.text_area :body, size: "60x10" %>
     <%= form.submit %>
    <% end %>
    

    Outputs:

    <form action="/articles/42" method="post" accept-charset="UTF-8" >
      <input name="authenticity_token" type="hidden" value="..." />
      <input type="text" name="article[title]" id="article_title" value="My Title" />
      <textarea name="article[body]" id="article_body" cols="60" rows="10">
        My Body
      </textarea>
      <input type="submit" name="commit" value="Update Article" data-disable-with="Update Article">
    </form>
    

    There are several things to notice here:

    • The form action is automatically filled with an appropriate value for @article.

    • The form fields are automatically filled with the corresponding values from @article.

    • The form field names are scoped with article[...]. This means that params[:article] will be a hash containing all these field's values. You can read more about the significance of input names in chapter Understanding Parameter Naming Conventions of this guide.

    • The submit button is automatically given an appropriate text value.

    So as you can see all field names are scoped as name="article[title]", name="article[body]", etc.

    It means that in backend params will be scoped with key article: { title: "My Title", body: "My Body" }

    HTML ids are also scoped with model name: id="article_title", id="article_body", etc.

    URI for form action is automatically filled based on article ID: action="/articles/42"

    Form fields values are mapped with model instance attributes: value="My Title", <textarea ...>My Body</textarea>, etc.

    Form also checks if model instance persists or no. Depending on this fact form method (POST or PATCH) and submit default value (create or update) are chosen

    You don't need to write it explicitly. Just use :model key for the form and pass attribute names to form input helpers

    In summary, "scoped" in this context means that the form is tightly integrated with given model object, and it operates in a way that is directly tied to that model's attributes, incapsulate form params with specific key