Reputation: 2497
In my have app I have a concept of notes... On the page I list out all the notes with an edit button. This edit button opens up a modal for editing the note. This all works great except for one big problem. If I have 5 notes, when I click the first edit button, it edits the first note as expected... However if I click on the second edit button, it ALSO edits the first note INSTEAD of the second. Same for the third, etc. Basically no matter what edit button I click I am always editing the first note.
User controller
def show
@user = User.find(params[:id])
@notes = @user.notes.order('created_at DESC')
end
Index page
<% @notes.each do |note| %>
<td><%= note.body %></td>
........
<td>
<%= button_tag text, class: "btn btn-primary", data: {toggle: "modal", target: "#edit_note"} %>
<%= render partial: "edit_note_modal", locals: { note: note } %>
</td>
<% end %>
Note Modal
<div class="modal fade" id="edit_note" tabindex="-1" role="dialog" aria-labelledby="edit_note" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Note</h4>
</div>
<div class="modal-body">
<%= form_for note do |f| %>
<div class="form-group">
<label for="keyword">Keyword</label>
<%= select_tag :keyword, options_for_select(<SOME FUNCTION>, selected: note.keyword ), class:"form-control" %>
</div>
<div class="form-group">
<label for="body">Body</label>
<%= text_area_tag :body, note.body , class:'form-control' %>
</div>
<div class="modal-footer">
<%= submit_tag "Update Note", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
</div>
Upvotes: 0
Views: 810
Reputation: 11137
That is because you use the same ID and ID should be uniq so when it search for the ID in the index page once it hit the first Note with that ID edit_note
it will open it, what you can do is have different Id for each view as following:
index page:
<%= button_tag text, class: "btn btn-primary", data: {toggle: "modal", target: "#edit_note_#{note.id}"} %>
Note Modal:
<div class="modal fade" id="edit_note_#{note.id}" tabindex="-1" role="dialog" aria-labelledby="edit_note" aria-hidden="true">
Note how the id now is edit_note_#{note.id}
and the edit button try to open model with same target edit_note_#{note.id}
Upvotes: 1