Synchronizing a list of checked and unchecked items
Example showing a list of available premium_licenses, and have the ones checkmarked that are chosen, as well as update the chosen set with newly checked and unchecked items.
class Client::SiteController < Client::ApplicationController
after_action :notify_admin
def update
@site = Site.find params[:id]
update_site_premium_licenses
end
private
def update_site_premium_licenses
ids_before = @site.bulk_premium_license_ids
@site.bulk_premium_license_ids = site_params[:bulk_premium_license_ids].select { |x| x.to_i > 0 }
ids_after = @site.bulk_premium_license_ids
@licenses_added = ids_after - ids_before
@licenses_removed = ids_before - ids_after
@site.save
!@site.errors.present?
end
def notify_admin
AdminNotification.with(remove: @licenses_removed, add: @licenses_added, site: @site).deliver(email_address)
end
def site_params
params.require(:site).permit(bulk_premium_license_ids: [])
end
The view is a collection of check-boxes and a submit button. CSS classes reference Bulma.
<%= form_with model: [:client, site] do |form| %>
<div class="field has-check">
<div class="field">
<p><%= t("subscriptionsDir.licenses.explainer") %></p>
</div>
<div class="field">
<div class="control">
<%= collection_check_boxes(:site, :bulk_premium_license_ids, BulkPremiumLicense.all, :id, :title) do |b| %>
<%= b.label(class: "b-checkbox checkbox", for: nil) do %>
<%= b.check_box(checked: site.bulk_premium_license_ids.include?(b.object.id)) %>
<%= tag.span class: "check is-primary" %>
<%= tag.span b.object.title, class: "control-label" %>
<% end %>
<%= tag.br %>
<% end %>
</div>
</div>
<div class="field">
<div class="control">
<%= form.submit t("subscriptionsDir.licenses.submit"), class: "button is-primary" %>
</div>
</div>
</div>
<% end %>
Notifications are being sent via noticed gem.