I'm creating checkboxes in a form that represent the notification methods a user is subscribed to, and that allow a user to subscribe to additional notification methods or unsubscribe from existing ones. Here's what the relationships look like:
class User
has_many :subscriptions, dependent: :destroy
accepts_nested_attributes_for :subscriptions, allow_destroy: true
end
and...
class Subscription
enum method: [:email, :txt]
enum category: [:order_confirmation, :order_update]
belongs_to :user
validates :category, :method, presence: true
end
The form I'm working in uses form_tag
.
If the user unchecks any of the checkboxes, I want the matching subscription to be deleted. I'm not sure if the best approach here is to use a _destroy
attribute or to prevent all attributes for that checkbox from being sent to the server.
If it's the former, I guess I could create a hidden field for _destroy
, but I have no idea how to conditionally set that hidden field to true depending on whether or not the checkbox is checked.
If it's the latter, I can't figure out how to NOT send my hidden fields along when a checkbox is unchecked. I need to include a hidden_field
for the subscription's id
so Rails doesn't create a new subscription if one already exists, as well as a hidden_field
for the subscription's category
so the correct type of subscription can be created.
Here's what the checkboxes I've created look like. Right now, I'm just creating checkboxes for the order_update
notification type:
<% [{ label: "Email", value: "email" }, { label: "Text message", value: "txt" }].each_with_index do |options, index| %>
<% existing_subscription = current_user.subscriptions.order_update.where(method: options[:value]) %>
<%= fields_for "user[subscriptions_attributes][]", existing_subscription.first_or_initialize, index: index do |t| %>
<%= t.hidden_field :category, value: :order_update %>
<%= t.check_box :method, { checked: existing_subscription.any?, include_hidden: false }, options[:value] %>
<%= t.label :method, options[:label] %>
<%= t.hidden_field :id %>
<% end %>
<% end %>
If I'm currently subscribed to both email and text notifications, and then I uncheck the box for text, this is what I get in my params:
"subscriptions_attributes"=>{"0"=>{"category"=>"order_update", "id"=>"1"}, "1"=>{"category"=>"order_update", "method"=>"email", "id"=>"2"}}