Skip to content

Instantly share code, notes, and snippets.

@swanson
Last active February 18, 2021 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swanson/cd722b1024ece647de7b0ae292b7cb74 to your computer and use it in GitHub Desktop.
Save swanson/cd722b1024ece647de7b0ae292b7cb74 to your computer and use it in GitHub Desktop.
Modal forms with Rails UJS
<h1>Posts</h1>
<ul>
<% Post.all.each do |p| %>
<li><%= p.title %></li>
<% end %>
</ul>
<%= link_to "+ Post", new_posts_path, remote: true %>
class PostsController < ApplicationController
def new
@post = Post.new
render :as_modal, locals: { template: :form }
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: "Done!"
else
render :as_modal, locals: { template: :form }
end
end
end
var existingModal = document.querySelector("[data-controller='modal']");
if (existingModal) {
document.body.removeChild(existingModal);
}
document.body.insertAdjacentHTML("beforeend", "#{j render partial: template.to_s, locals: local_assigns }");
<div class="modal" data-controller="modal">
<%= form_with model: @post, local: false do |form| %>
<%= f.label :body %>
<%= f.rich_text_area :body %>
<%= f.submit %>
<% end %>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment