Last active
February 18, 2021 02:47
-
-
Save swanson/cd722b1024ece647de7b0ae292b7cb74 to your computer and use it in GitHub Desktop.
Modal forms with Rails UJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Posts</h1> | |
<ul> | |
<% Post.all.each do |p| %> | |
<li><%= p.title %></li> | |
<% end %> | |
</ul> | |
<%= link_to "+ Post", new_posts_path, remote: true %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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