1

So..I’m trying to understand usage of modals in Rails and looking for a few pointers.

I have a list of items at at category/1 which are being displayed in a loop. I have a modal which I’m rendering at the bottom of the page with <%= render "category/update_item_modal" %>

There’s already a form setup for updating params of each item, but I’m trying to get a modal pop up to specifically just update the title. The modal popup works, and so far I have the following for the button which opens the modal:-

<a href="#" data-toggle="modal" data-target="#updateItemModal-<%= title.id %>"><button class="btn btn-primary btn-sm">Edit Title</button></a>

And the modal itself:-

<div class="modal fade" id="updateItemModal-<%= item.id %>" tabindex="-1" role="dialog" aria-labelledby="updateItemModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="updateItemModalLabel">Change Item</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <!-- UPDATE TITLE HERE? -->
      </div>
    </div>
  </div>
</div>

This gives me the error of undefined local variable "id" from the modal id for obvious reasons, and this is where my understanding hits a wall. How do I pass the data from a loop iteration into my modal?

End goal is to have an editable textarea field with the existing title in it, and a submit button which will post the edit.

Taplar
  • 24,788
  • 4
  • 22
  • 35
s89_
  • 1,533
  • 3
  • 25
  • 40

1 Answers1

1

Provided you have defined @item in your controller:

<%= render "category/update_item_modal", locals: item: @item %>

Then you have access to item in your partial. One more thing you can do to avoid that error is to use the safe operation operator item&.id. More on the safe navigation operator here: https://bugs.ruby-lang.org/issues/11537

NM Pennypacker
  • 6,704
  • 11
  • 36
  • 38
  • Awesome, thanks! What's the term for what you did with `item&.id`? I've seen this before but want to read up on it further. – s89_ May 02 '19 at 15:34
  • 1
    That's the safe navigation operator. I added a link, but there are a few helpful answers here: https://stackoverflow.com/questions/36812647/what-does-ampersand-dot-mean-in-ruby – NM Pennypacker May 02 '19 at 15:40
  • Great, thanks. I had to wrap the above like so `{item: item}` for it to work. Next issue is that I don't have @item in my controller as there's about 100 of them on the `show` page I'm working on... I only have access to @category which holds all the items. – s89_ May 02 '19 at 15:55