Rails: Conditional nested attributes in edit form

Sso*_*esS 2 nested-attributes ruby-on-rails-4

I have a model called Offer and another called PurchasinGroup

Offer has many PurchasingGroups

Offer accepts nested attributes for PurchasingGroups

While creating an offer you can add as many PurchasingGroups as you want.

PurchasingGroup has a boolean attribute called active.

while editing an Offer you can see all the created PurchasingGroups, however I want to let the user edit only the PurchasingGroups that are active, and do not display the inactive purchasing groups.

This is my edit action in offers_controller.rb:

def edit
  @offer = Offer.find(params[:id])
end
Run Code Online (Sandbox Code Playgroud)

And this is my form (only the part that matters):

<fieldset>
        <legend>Purchasing groups</legend>
        <%= f.fields_for :purchasing_groups do |builder| %>
            <%= render partial: 'purchasing_group_fields', locals: { f: builder } %>
        <% end %>
    </fieldset>
Run Code Online (Sandbox Code Playgroud)

In the edit form all the purchasing groups are being shown for edit, I want to show only those that are active I mean purchasing_group.active == true

How is the best way to do it?

ric*_*her 5

<%= f.fields_for :purchasing_groups, @offer.purchasing_groups.where(active: true) do |builder| %>
    <%= render partial: 'purchasing_group_fields', locals: { f: builder } %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

另一方面,您也可以在模型中添加关联

class Offer
    has_many :active_purchasing_groups, class_name: "PurchasinGroup", -> { where(active:true) }
    ...
end
Run Code Online (Sandbox Code Playgroud)

然后

<%= f.fields_for :active_purchasing_groups do |builder| %>
    <%= render partial: 'purchasing_group_fields', locals: { f: builder } %>
<% end %>
Run Code Online (Sandbox Code Playgroud)