Her*_*nHH 5 forms ajax jquery ruby-on-rails ruby-on-rails-4
我在 Rails 4 中使用 remote: true 创建了一个 ajax 表单。由于某种原因,我失踪了,我的验证错误没有显示在表单中。
这是我当前的代码库:
1.表格
= simple_form_for @foo, url: foos_path, as: :foo, remote: true do |f|
.row
.input-field
= f.input :bar
.right-align.card-button
= f.button :submit, class: "waves-light blue", data: { disable_with: "Loading..." }
Run Code Online (Sandbox Code Playgroud)
2.create.js.erb
$("#new_foo").html('<%= j render_cell :foo, :form, foo: @foo %>');
Run Code Online (Sandbox Code Playgroud)
3. 控制器
def create
@foo = FooForm.new( Foo.new )
respond_to do |format|
if @foo.validate(params[ :country ])
@foo.save
format.html { redirect_to root_path }
format.json { render :show, status: :created, location: @foo.model }
format.js
else
format.html { render :new }
format.json { render json: @foo.errors, status: :unprocessable_entity }
format.js
end
end
end
Run Code Online (Sandbox Code Playgroud)
我希望此代码在错误提交后显示验证错误。然而,由于某种原因,提交错误后没有任何反应。我可以确认表单正在提交,但是因为提交是在日志中处理的。当我删除远程提交时,我还可以确认表单工作正常。
有什么我想念的吗?
附注。我正在使用改革gem,这可能会使我的控制器对象代码对很多人来说有点陌生。我正在按照这个gem在我的 js 文件中渲染一个单元格
更新 我在这方面又挣扎了一些。我实现了一个解决方案,我复制了我在以前的应用程序中逐字创建的“远程:真实”解决方案。这在我以前的应用程序中完美无缺,但在我的新应用程序中没有显示验证错误。这两个应用程序之间的唯一区别是 Ruby 和 Rails 的版本。
在第一个应用程序中,我运行 Ruby: 2.2.1 和 Rails: 4.2.2。我的新应用程序(“我无法使用的应用程序”)我正在运行 Ruby:2.2.3 和 Rails:4.2.4。
这可能会产生影响吗??
几个小时后,我终于设法解决了这个问题。仍然不确定为什么会发生这种情况,但我在这里提出答案,以防其他人经历过类似的事情。这个Stackoverflow 答案使我朝着正确的方向前进。
我需要将此行添加到我的创建操作中:
format.js { render layout: false, content_type: 'text/javascript' }
Run Code Online (Sandbox Code Playgroud)
因此,我的完整创建操作现在如下所示:
def create
@foo = FooForm.new( Foo.new )
respond_to do |format|
if @foo.validate(params[ :country ])
@foo.save
format.html { redirect_to root_path }
format.json { render :show, status: :created, location: @foo.model }
format.js
else
format.html { render :new }
format.json { render json: @foo.errors, status: :unprocessable_entity }
format.js { render layout: false, content_type: 'text/javascript' }
end
end
end
Run Code Online (Sandbox Code Playgroud)