[英]ajax rails form_with submits but only after page reload
我在资源show.html.erb
上有一个现有的评论表单,我想将其添加到显示页面而无需重新加载整个页面。 我知道通过“form_with”表单使用ajax,这应该是完全可能的。
我的问题是,虽然表单确实创建了一个新评论,但它仅在我刷新页面后才会出现。
我也收到以下错误。
ArgumentError(参数太少):
app/controllers/comments_controller.rb:18:in 'format' app/controllers/comments_controller.rb:18:in 'create'
评论控制器
class CommentsController < ApplicationController
before_action :load_commentable
before_action :authenticate_user!
before_action :comment_auth, only: [:edit, :update, :destroy]
...
def create
@comment = @commentable.comments.new(allowed_params)
@comment.user_id=current_user.id if current_user
if @comment.save
format.html { redirect_to @commentable, notice: "Comment added." }
format.js
else
render 'edit'
end
...
意见/评论/create.js.coffee
comment = document.getElementById("comment")
comment.innerHTML = "<%= j render(@comment) %>"
意见/评论/_form.html.erb
<%= form_with(model: [@commentable, @comment]) do |f| %>
<% if @comment.errors.any? %>
<div class="error_messages">
<h2>Please correct the following errors.</h2>
<ul>
<% @comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<strong><%= f.label :name, :class=>'form-label' %></strong><br>
<%= f.text_field :name, value: current_user.fname, readonly: true, :class=>'form-control' %>
</p>
<p>
<strong><%= f.label :title, :class=>'form-label' %></strong><br>
<%= f.text_field :title, :class=>'form-control' %>
</p>
<p>
<strong><%= f.label :review, :class=>'form-label' %></strong><br>
<%= f.text_area :body, :class=>'form-control', rows: 5 %>
</p>
<p>
<%= f.submit :class=>'btn btn-success' %>
</p>
<% end %>
如您所知, form_with
它是一个远程表单,您不应该在那里使用redirect_to
。 请删除您的阻止
if @comment.save format.html { redirect_to @commentable, notice: "Comment added." } format.js else render 'edit' end
将其替换为
if @comment.save @status = "success" end
并且您可以在@status(失败/成功)条件下向您的views/comments/create.js.erb
(它不是.js.coffee)添加一条通知消息。
希望这会有所帮助。
对我来说,我需要
<%= form_with(model: @message, method: :post, local: true) do |f| %>
本地: true 是必要的。 所有其他组合都不起作用远程:真,远程:假,本地:假
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.