Skip to content

Instantly share code, notes, and snippets.

@josephbridgwaterrowe
Created March 19, 2016 19:43
Show Gist options
  • Save josephbridgwaterrowe/25acaaa01b124f42ed0d to your computer and use it in GitHub Desktop.
Save josephbridgwaterrowe/25acaaa01b124f42ed0d to your computer and use it in GitHub Desktop.
twitter bootstrap popup modals with Rails JS ERB (ActiveRecord Model)
<% html = render partial: 'partial_to_render',
locals: { my_model: my_model } %>
$.unblockUI();
$('.modal').modal('hide');
$('#my-element').html('<%=j html %>');
$.jGrowl('<%= t(message) %>', { theme: 'alert-success' });
<div class="modal fade"
id="modal"
tabindex="-1"
role="dialog"
aria-labelledby="modal_label"
aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<%= simple_form_for(my_model,
defaults: {
label_html: { class: 'col-sm-4' },
input_wrapper_html: { class: 'col-sm-4' }
},
html: {
class: 'form-horizontal block',
remote: true,
role: 'form'
},
wrapper: :horizontal_form) do |form| %>
<div class="modal-header">
<button type="button"
class="close"
data-dismiss="modal"
aria-hidden="true">
&times;
</button>
<h4 class="modal-title">
<%= t('.title') %>
</h4>
</div>
<div class="modal-body">
<%= error_messages(my_model) %>
<%= form.input :my_field %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
<%= t('links.cancel') %>
</button>
<input type="submit" class="btn btn-primary"
value="<%= t('links.save') %>" />
</div>
<% end %>
</div>
</div>
</div>
var $element = $('<%=j render partial: 'new', \
locals: { my_model: my_model } %>');
if ($('#modal').length == 0) {
$('body').append($element);
$element
.modal()
.on('shown.bs.modal', function () {
setupModal();
$('.modal input[type=text][name]:first').focus()
})
.on('hidden.bs.modal', function () { $(this).remove(); });
} else {
$('.modal-body').replaceWith($element.find('.modal-body'));
setupModal();
}
function setupModal() {
$.unblockUI();
}
class MyModelsController < ApplicationController
respond_to :js
def create
render_new and return unless my_model.valid?
if my_model.save
render :create,
locals: { message: '.success' }
else
render_new
end
end
def render_new
render :new, locals: { my_model: my_model }
end
def my_model
@my_model ||= MyModel.new(my_params)
end
def my_params
return {} unless params[:my_model]
params.require(:my_model).permit(:my_field)
end
end
<%= link_to t('links.new_label'),
new_model_path,
class: 'btn btn-link block',
remote: true %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment