ROR pass params to modal

sotn picture sotn · Jan 20, 2016 · Viewed 9k times · Source

I'm trying to open a modal that displays a list of items. The list of items is already available in the view as a variable. How do I pass this variable to the modal?

Below is roughly how the main view looks like:

View.html.erb

<div>
  <%= @users.each do |user|%>
    <h1>user.name</h1>
    <h2>user.email</h2>
    <%= link_to remote: true, 'data-toggle' => 'modal', 'data-target' => '#taskModal do %>           
      <i><%= user.tasks.count%></i>
    <% end %>
  <% end %>
</div>

<div class="modal" id="taskModal" aria-hidden="true">
...
<%= render partial: 'list_modal' %>

list_modal is a partial with the structure of the modal.

Answer

x6iae picture x6iae · Jan 20, 2016

As opposed to having the list of items already on the view, and wanting to pass it to the modal, One thing you can do is make the button ( or link ) for opening the modal to call a controller action by ajax, and then let the action respond to JS, where you will now use the corresponding view.js file to both populate the modal as well as programmatically render it ( after populating it ).

Example:

Link to open modal:

<%= link_to "Open users list", users_open_list_modal_path, remote: true %>

Users open list modal controller action:

def open_list_modal
  @user_list = User.all
  respond_to do |format|
    format.js
  end
end

open_list_modal.js.erb:

#populate modal
$('#modal').html('#{ escape_javascript(<%= render partial: 'user_list', locals: {user_list: @user_list} )}');

#render modal
$('#modal').openModal();

And then on the modal itself, you can now have access to the user_list (NOT @user_list) list.

Note: In this example, I made use of both erb, js, and material-modal. If you are using something different from these ( maybe slim, haml, coffee, bootstrap...), you will have to suite the example to your case.

Hope this helps.