Clear all nested models if the parent has a field of a specific value

Trying to figure out the best way to clean up nested models if its parent has a specific value field.

I have models Company

, Person

and Role

. The company has_many people

and the person can be a contractor, which is determined by a boolean value set in the table people

set by the following switch:

<%= f.input :contractor, as: :radio_buttons, label: 'Is this person a contractor?', input_html: { class: 'entity_tf form-control rtf radio radio-false' } %>

      

Now when the user clicks Yes, the user is presented with a button with which they can add dynamic cocoon fields listing the roles that human contractor has.

My question is:

Suppose that after adding a role group, the user suddenly realizes that the person he was editing was not actually a contractor (or something like that) and decided to change the switch to No. As I established this, the radio fields will simply be hidden. This means they will be saved after the form is submitted. How can I better remove them after submitting the form if the radio button is set to false? I am thinking of adding some conditional / validations to the model.

thanks for any ideas.

+3


source to share


1 answer


Use callback in your Person model.



after_save :remove_all_roles, unless: :is_a_contractor_bool?

def remove_all_roles
    self.roles.delete(self.roles)
end

      

+1


source







All Articles