Do not use hidden_field fields in nested forms

1

I would like to know if there is a better way to work with nested attributes without having to send the id of the parent object through the hidden_field field, I find it unsafe to leave this to the page.

Suggestions? Here is the code used:

<%= form_for(@responsible, :url => (@responsible.new_record? ? enterprise_responsibles_path(@responsible.enterprise) : enterprise_responsible_path(@responsible.enterprise, @responsible))) do |f| %>
<% if @responsible.errors.any? %>
<div id="error_explanation">
    <h2><%= pluralize(@responsible.errors.count, "error") %> prohibited this responsible from being saved:</h2>
    <ul>
        <% @responsible.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
        <% end %>
    </ul>
</div>
<% end %>

<%= f.hidden_field :enterprise_id %> #ID DO OBJETO PAI ENVIADO VIA HIDDEN**
<div class="form-group">
    <%= f.label :name %>
    <%= f.text_field :name, :class => "form-control" %>
</div>
<div class="form-group">
    <%= f.label :cpf %>
    <%= f.text_field :cpf, :class => "form-control" %>
</div>

<div class="form-group">
    <%= f.label :occupation %>
    <%= f.text_field :occupation, :class => "form-control" %>
</div>

<%= f.check_box :active %>&nbsp;<%= f.label :active %>

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">Contacts
            <span class="btn-group btn-group-xs pull-right"> 
                <%= link_to_add_fields content_tag(:i, "", class:"glyphicon glyphicon-plus") + " add contact", f, :contacts, "btn btn-xs btn-success pull-right" %>
            </span>
        </h3>
    </div>
    <div class="panel-body">
        <%= f.fields_for :contacts do |builder| %>
        <%= render 'contact_fields', f: builder %>
        <% end %>
    </div>
</div>

<div class="actions">
    <%= f.submit class: "btn btn-sm btn-primary" %>
</div>
<% end %>

routes.rb

resources :enterprises do
    resources :responsibles do
      resources :contacts  
    end
    resources :proposals
end
    
asked by anonymous 12.02.2014 / 17:22

1 answer

1

So, responding formally,

Switch

<%= form_for(@responsible, :url => (@responsible.new_record? ? enterprise_responsibles_path(@responsible.enterprise) : enterprise_responsible_path(@responsible.enterprise, @responsible))) do |f| %>

By

<%= form_for([@enterprise, @responsible], :url => (@responsible.new_record? ? enterprise_responsibles_path(@responsible.enterprise) : enterprise_responsible_path(@responsible.enterprise, @responsible))) do |f| %>

and remove the hidden field.

    
12.02.2014 / 20:34