I’m using Stimulus ina Rails (5.2) app and I have created a controller to manage Tag
s (A Project
have many Tag
s).
Within the controller, I currently display the form used to add a Tag
,
<div class='' data-controller='tags'>
<div class='tags'>
<%= render @project.tags %>
<div class='' data-action='click->tags#displayForm' data-target='tags.addButton'>add tag</div>
</div>
<%= form_with model: Tag.new, url: project_tags_path(@event) do |f| %>
<div class='' data-target='tags.form'>
<%= f.text_field :name, class: '', data: { action: 'keyup->tags#toggleSubmitButton', target: 'tags.textField' } %>
<%= button_tag 'add tag', type: 'submit', class: '', data: { target: 'tags.submitButton' } %>
<%= tag.a 'dismiss', class: '', data: { action: 'click->tags#hideForm', target: 'tags.dismissButton' } %>
</div>
<% end %>
</div>
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["form", "addButton", "submitButton", "textField"]
connect() {
...
}
displayForm() {
...
}
hideForm() {
...
}
toggleSubmitButton() {
...
}
}
Now I’d like to add the ability to delete a tag by clicking on a button inside the tag.
#_tag.html.erb
<div class=''>
<%= tag.name %>
<button class=''></button>
</div>
My first idea was to add this functionality to the TagsController
as follows
<div class=''>
<%= tag.name %>
<button class='' data-action='click->tags#deleteTag' data-target='tags.deleteButton'></button>
</div>
However, this works only for the first Tag
.
So, what is the preferred way to deal with repeated elements (partials)?
Should I have a controller dedicated to deleting the Tag
like below
<div class='' data-controller="deleteTags">
<%= tag.name %>
<button class='' data-action='click->deleteTags#deleteTag' data-target='deleteTags.deleteButton'></button>
</div>
Having already all the logic related to the creation in the TagController
it makes sense to me to keep also the one responsible for deleting Tag
s in same controller.