Skip to content

Instantly share code, notes, and snippets.

@fongfan999
Forked from dbridges/_comment.html.slim
Created November 22, 2018 04:05
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 fongfan999/c9bbfc83754178cb5665e4dcd609a02b to your computer and use it in GitHub Desktop.
Save fongfan999/c9bbfc83754178cb5665e4dcd609a02b to your computer and use it in GitHub Desktop.
Stimulus.js and Rails remote forms with error handling
- # app/views/comments/_comment.html.slim
li data-controller="comment" data-action="click->comment#hello"
= "#{comment.message} by #{comment.user.email}"
- # app/views/comments/_error.html.slim
- comment.errors.full_messages.each do |error|
li = error
// app/javascript/controllers/comment_list_controller.js
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["text", "commentList", "commentErrors"]
onPostSuccess(event) {
let [data, status, xhr] = event.detail;
this.commentListTarget.innerHTML += xhr.response;
this.textTarget.value = "";
this.commentErrorsTarget.innerText = "";
}
onPostError(event) {
let [data, status, xhr] = event.detail;
this.commentErrorsTarget.innerHTML = xhr.response;
}
}
# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def index
@comments = Comment.all
end
def create
@comment = current_user.comments.create(comment_params)
if @comment.errors.any?
render partial: 'error', comment: @comment, status: :bad_request
else
render @comment
end
end
private_error
def comment_params
params.require(:comment).permit(:message)
end
end
- # app/views/comments/index.html.slim
h1 Comments
.comment-list data-controller="comment-list"
ul.comment-errors data-target="comment-list.commentErrors"
ul.comments-list data-target="comment-list.commentList"
= render @comments
= bootstrap_form_with model: Comment.new,
html: { data: { type: "html",
action: "ajax:success->comment-list#onPostSuccess ajax:error->comment-list#onPostError" } } do |form|
= form.text_area :message, hide_label: true, placeholder: "New comment...", data: { target: "comment-list.text" }
= form.submit "Post Comment"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment