Route a Rails modal view

0

Greetings! Is there any way to route a modal view? Imagine that they are in the index of X resource, click on a record, the normal modal comes out, but I need that modal to have a url reflected in the address bar as FB offers the url of that modal, I have thought taking advantage of that show view is routed, make it modal, only that show view must be displayed in the index and not within its own individual route

Specifically, what I need is the following, I am in the companies view, when I click on a company, it is displayed with a modal, but I need that when the url is displayed it changes to the one of the record shown in the modal , I hope you can give me help greetings!

    
asked by Hector Hernandez 19.06.2017 в 22:46
source

2 answers

0

You can use history.pushState() to change the URL of the browser ( without reloading the page).

For example, you could use a script like the following 1 :

<button id="boton">Mostrar modal</button>
<div id="mi-modal" tabindex="-1" role="dialog" class="modal fade"></div>

<script>
  $("#boton").click(function() {
    $("#mi-modal").html("PRUEBA");
    $('#mi-modal').modal("show");
    history.pushState({}, '', url_recurso);
  });

  $('#mi-modal').on('hidden.bs.modal', function() {
    history.pushState(null, null, url_index);
  });
</script>

In this example, clicking on the button will open a modal with the text "PRUEBA" as content and change the URL to the value set in url_recurso ; and when closing the modal, you will return to the previous URL with url_index (considering that url_index is the URL of your index ).

The adaptation to your particular case depends on how you have your code and how to show the manners. Assuming you do it with AJAX, then you could put the first part of script in your show.js.erb :

$("#mi-modal").html("<%= j(render 'form') %>");
$('#mi-modal').modal("show");
history.pushState({}, '', <%= j(@url_recurso) %>);

And, instead of a text, you could include a view (in this example, I show the partial _form.html.erb ), which would have the content you want to show.

It is important to generate also the same view in html , that is to say show.html.erb , so that the users to whom the URL is shared can visit it:

<%= render 'form' %>

And finally, in your controller you must specify the two formats ( js and html ) to which you must respond, as well as define the value of @url_recurso used in your view js :

def show
  # ...
  @url_recurso = "url/recurso/12"

  respond_to do |format|
    format.html # show.html.erb
    format.js   # show.js.erb
  end
end

1 I use bootstrap and jQuery for manners and events.

    
answered by 20.06.2017 / 03:55
source
0

Solved! Thanks to Gerry! It works great! I leave my updated gist for future references: link

    
answered by 22.06.2017 в 23:39