sparkle
sparkle

Reputation: 7400

Simple form remove associated record

I'm using simple_form and I would give user ability to quickly remove an associated record. (eg. "checking/uncheking") How is it possibile with simple_form? Is there another gem to help with this?

Parent has many children

<%= simple_form_for @parent do |f| %>

  <%= f.simple_fields_for :childens do |p| %>
    <%= p.input :title, as: :boolean %>
  <% end %>

<% end %>

Rails 5.2

Upvotes: 2

Views: 770

Answers (1)

Svetlin Simonyan
Svetlin Simonyan

Reputation: 345

You don't need another gem for that. There are several things you need to do:

  • Add allow_destroy: true to the accepts_nested_attributes_for :children in the parent model
  • Add a <%= p.input :_destroy, as: :boolean %> to the nested form
  • Whitelist the _destroy pseudo attribute in your controller by listing it in children_attributes in the permit call

Essentially this is a feature of Rails' accepts_nested_attributes_for - it sets up the children_attributes setter to not only create/update associated records but also delete them in the presence of _destroy in the passed hash.

Upvotes: 2

Related Questions