[英]Rails 7 ActionController::UnknownFormat in CommentsController#create respond_to
I have a comments controller that i want to load a partial "create.js.erb"我有评论 controller 我想加载部分“create.js.erb”
class CommentsController < ApplicationController
skip_before_action :verify_authenticity_token
def create
@comment = Comment.new(comment_params)
@comment.account_id = current_account.id
respond_to do |format|
if @comment.save
@comments = Comment.where(post_id: @comment.post_id)
format.js { render "comments/create" }
else
# unable to save
end
end
end
def comment_params
params.require(:comment).permit(:message, :post_id)
end
end
My create.js.erb partial我的 create.js.erb 部分
console.log("comment created...");
$("#post-comments").html("<%= escape_javascript(render partial: 'posts/comments', locals: { comments: @comments }) %>");
If i refresh the page the comment gets posted however when i click the submit button it send me the error ActionController::UnknownFormat in CommentsController#create如果我刷新页面,则会发布评论,但是当我单击提交按钮时,它会在 CommentsController#create 中向我发送错误 ActionController::UnknownFormat
In laymans terms i want the create function to hit without having to redirect.用外行的话来说,我希望 create function 无需重定向即可命中。
Seems like using Hotwire and Turbo is the way to go似乎使用 Hotwire 和 Turbo 是通往 go 的方式
respond_to do |format|
if @comment.save
@comments = Comment.where(post_id: @comment.post_id)
format.html { redirect_to posts_path }
format.turbo_stream
end
end
then you need to change create.js.erb to create.turbo_stream.erb那么你需要将 create.js.erb 更改为 create.turbo_stream.erb
<%= turbo_stream.prepend "comments", @comments %>
all works as intended now现在一切正常
Rails 7 removes the previous way of using format.js in Rails UJS and now it's all hotwire/turbo. Rails 7 取消了以前在 Rails UJS 中使用 format.js 的方式,现在都是 hotwire/turbo。 Kinda confusing but once you learn it no more writing javascript. :)有点令人困惑,但一旦你学会了就不再写 javascript。:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.