ruby-on-railsform-forform-helpers

How are parameters sent when I use instance variables in form_for in rails


I am little bit confused on how the parameters are sent to the controller through form_for in rails. I read dealing with model objects section in https://guides.rubyonrails.org/form_helpers.html and tried to understand a bit but it did not help me much. Basically I have a form like below

<%= form_for @flow, url: '/create_flow' do |f| %>
  <%= f.hidden_field :action_id, value: @selected_action.id %>
  <table class="table table-striped table-bordered table-hover">
    <tr>
      <th>Flow name</th>
      <th>URL</th>
    </tr>
    <% @selected_action.missed_call_flows.each do |flow| %>
      <tr>
        <td><%= flow.name %></td>
        <td><code><%= flow.url %></code></td>
      </tr>
    <% end %>
    <tr class="form-group">
      <td>
        <%= f.text_field :name, class: "form-control", placeholder: "Add a new flow ...", required: true %>
      </td>
      <td>
        <button type="submit" class="btn btn-primary">Generate URL</button>
      <td>
    </tr>
  </table>
<% end %>
<% end %>

And the corresponding controller is accessing parameters as params[:missed_call_flow][:action_id]

My question is from where did params[:missed_call_flow] come into play when it is not mentioned anywhere in the form. What I understood from the documentation is, when instance variable is given in form, for example it is @flow here, the params can be accessed as params[:flow]. Then why in this code it is [:missed_call_flow] and not [:flow] ? Is this also one of the way of accessing because the controller name is MissedCallFlowController?

This is a sample application that I'm trying to understand for my project and the person who wrote the code is currently not available so posting it here for help. Let me know if my question is missing any details.


Solution

  • The form_for helper creates a form from a model object. If you've set up your Rails app in the conventional way, you will have (it appears) a file called app/models/missed_call_flow.rb that begins by defining class MissedCallFlow.

    This file defines the model. It is the source of the params[:missed_call_flow] name, because it is the convention in Rails to name this data structure for the model.

    As a generalization in programming, the variable name should not impact the functioning of the program. The fact that you have named your variable @flow is ignored by the inner workings of your program. It is a convenience to the programmer to be able to name your variable whatever you want.

    I wonder if you are not seeing the model name you expect because missed_call_flow represents a join table between two other tables with models named missed_call and flow. You might be assigning an instance of this MissedCallFlow class to the variable @flow by mistake.