How to open post Show page in a modal with Ruby on Rails 5
Asked Answered
G

1

6

My homepage displays a list of posts and when I click a post, it open as a new page,

but I need to stay at the homepage and open post Show page as modal. Any idea how?

Thank you

Glazer answered 18/11, 2017 at 0:42 Comment(2)
Probably the most efficient way to do this is to use AJAX. You would send an AJAX request to the server and then take the results and use it to populate a modal. If you only have a few posts on a page, you could simply render all of the modals on one page and then use javascript to hide and show them as appropriate.Solemn
hmm, thanks for the direction, I will research about AJAX then. I have hundreds of items.Glazer
S
15

Solution is with the assumption that you are using bootstrap...

change your show action for js requests

  def show
    @post = Post.find(params[id])
    respond_to do |format|
      format.js
    end
  end

add this div at the end of posts index

<div id='post-content'></div>

your link to show page must look something like this now

  <%= link_to 'View Post', post_path(post), remote: true %>

add a new file posts/show.js.erb

$('#post-content').html("<%= j render 'post_modal', post: @post %>");
$('#post-modal').modal('show');

add a partial posts/_post_modal.html.erb

<div id="post-modal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <div>
         --- put all your show.html.erb code here 
      </div>
    </div>
  </div>
</div>
Spelunker answered 18/11, 2017 at 10:15 Comment(8)
Thanks mate! I'm not using Bootstrap, I will still try to solve from your way. Thank youGlazer
wow! it actually worked! Thank you! I'm studying your approach to learn better now. Thank you! Btw do you have any suggestion on how can I keep the URL, so that it can be shared? Currently I get error i.imgur.com/9wjw720.pngGlazer
it seems like you have missed remote: true in your link_to tag <%= link_to 'View Post', post_path(post), remote: true %>Spelunker
happy to help..!Spelunker
Thanks again mate! I actually have the remote:true btw 🤔 <%= link_to image_tag(post.image_url.to_s), post_path(post), remote: true %>Glazer
its difficult for me to find the problem without looking at the code, please create a sample project on Github and push your code there (if you may).Spelunker
hmmm, I don't use GitHub. 🤦‍♂️ btw removing respond_to do |format| format.js end solved the issue. Now the show link works great, and modal still works 👍 I just need to apply URL to address bar somehow when we view post in modal.Glazer
Thanks, is there a name for this solution?Ophite

© 2022 - 2024 — McMap. All rights reserved.