rails fields for conditional

1.5k views Asked by At

I'm displaying some contacts for a case. the problem is I want to break them up into groups.

Clients ...list clients Former Attorney ...list former attorney Opposing Parties ...list Opposing Parties

    <% current_account.roles.each do |role| %>
      <%= f.fields_for :case_contacts, f.object.case_contacts.order(:role) do |builder| %>
        <% if builder.object.role == role %>
          <%= render partial: 'contact_fields', locals: { f: builder, edit: edit } %>
        <% end %>
      <% end %>
    <% end %>

So this works except that it leaves empty div.fields in my html.

Is there a way to put the conditional in the fields_for statement

    <%= f.fields_for :case_contacts, f.object.case_contacts.order(:role), if f.object.role = role do |builder| %>

I know this example is wrong.

And, in all actuality, I could do without the div.fields that fields_for generates all together

Edit: I guess I don't even need to order it if fields_for only displays fields where builder.object.role = role

2

There are 2 answers

1
Gambai On BEST ANSWER

Found the answer

 <%= f.fields_for :case_contacts, f.object.case_contacts.where(role: role) do |builder| %>
1
infused On

You'll have to wrap the fields_for block with your guard condition:

<% if f.object.role == role %>
  <%= f.fields_for :case_contacts, f.object.case_contacts.order(:role) do |builder| %>
    <% if builder.object.role == role %>
      <%= render partial: 'contact_fields', locals: { f: builder, edit: edit } %>
    <% end %>
  <% end %>
<% end %>