Anton Ipatov
Anton Ipatov

Reputation: 167

Ruby on rails bootstrap modal window

I have model Post.rb with title and description

My index page.

Title 1
Title 2
Title 3

I need a description opened in bootstrap modal window in the same page

index.html.erb

<ul class="content">
  <%= render @posts %>
</ul>

_post.html.erb

<li> 
  <%= link_to post.title, '#myModal', 'data-toggle' => 'modal' %>

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel"><%= post.title %></h4>
      </div>
      <div class="modal-body">
        <%= post.description %>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
</li>

Upvotes: 0

Views: 5856

Answers (1)

Anand
Anand

Reputation: 6531

_post.html.erb

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content" id="modal_content">
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
  1. create a partial _post_content.html.erb

    <div class="modal-header">
      <h4 class="modal-title" id="myModalLabel"><%= post.title %></h4>
    </div>
    <div class="modal-body">
      <%= post.description %>
    </div>
    

2.

<%= link_to post.title, show_modal_path(post_id: post.id), remote: true %>

3.

def show_modal
  @post = Post.find(params[:post_id])
end

4.show_modal.js.erb

$('#modal_content').html("<%= j render 'post_content', post: @post %>");
$("#myModal").modal('show');
  1. create route for show_modal ex-

get 'show_modal/:id', to: 'your_controller#show_modal', as: :show_modal_path

Upvotes: 3

Related Questions