After finish Ruby on Rails projects at Microverse, I had to work on the final Ruby on Rails project. It was a budget transaction web app π(repo), once I got the requirements I checked the required design, and I thought that it would be great to add a modal dialog, so I did.
1. Add gems
Add
gem bootstrap
andgem popperjs
to Gemfile. Then installbundle install
Go to
application.js
file and add, don't forget should be in this order//= require jquery //= require popper //= require turbolinks //= require bootstrap //= require_tree.
The
require
statement is used to call all bootstrap dependency in that order
2. Change view layouts
- Create a partial view
_new.html.erb
file add the content you want to use it. This is going to be modal view
# _new.html.erb
<div class="modal-header">
<h5 class="modal-title">Feed the piglet </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
`All modal content in here`
</div>
- And in the
index.html.erb
add the modal
# fab button
<div class="btn-group-fab" role="group" aria-label="FAB Menu">
<div>
<%= link_to '<button type="button" class="btn btn-main btn-secondary has-tooltip" data-placement="left" title="Menu"> <i class="fa fa-plus"></i> </button>'.html_safe, new_festival_path, {remote: :true, 'data-toggle': 'modal', 'data-target': '#modal-window'} %>
</div>
</div>
# modal element
<div id="modal-window" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content"></div>
</div>
</div>
- Create a new file javascript erb file
new.js.erb
# new.js.erb
$("#modal-window").find(".modal-content").html("<%= j (render 'new') %>");
$("#modal-window").modal();
With JQuery this file links the modal element with the new Rails route
3. Modify the controller
In the controller in the new method, add the respond_to
block to use AJAX
# festivals_controller.rb
def new
@festival = Festival.new
respond_to do |format|
format.html
format.js
end
end
And voila, now we have this
Conclusion
A modal will help us to avoid reloading to the next page and to return again to the same one. In the end, this is more intuitive for the final user. We keep in the same, complete the transaction and stay on the same page, keeping away from the backing and forth on pages.
I'm sure there are plenty of ways in order on how to do it, however, this is an easy way to achieve also is much more detailed information.
Leave a comment if you found this post helpful or liked it. Also, let me know if you have another approach to deal with the same issue
Follow me @btandayamo on Twitter
Taken from: dzone.com/articles/rails-creating-modals