Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 369
Designer Avatar asked Nov 18 '17 00:11

Designer


1 Answers

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>
like image 73
Sikandar Tariq Avatar answered Oct 22 '22 23:10

Sikandar Tariq