【问题标题】:Use the same rails form for AJAX and non AJAX calls对 AJAX 和非 AJAX 调用使用相同的 rails 形式
【发布时间】:2016-02-18 09:58:59
【问题描述】:

我有一个模型的 simple_form。新动作 si basic 的形式如下:

<%= simple_form_for @patient do |f| %>
    .... fields
<% end %>

我想在New 视图中使用此表单,但也想在带有 AJAX 的引导模式中使用。如果我使用这种语法:

<%= render partial: 'patients/form', locals: {patient: @patient, remote: true} %>

但是当我这样做时,我只能使用远程访问本地变量,而不是 @remote,这将在 new 视图中呈现错误。

编辑

对局部的调用:

<%= render partial: 'patients/form', locals: {patient: @patient, remote: true } %>

还有形式:

<%= simple_form_for @patient, remote: @remote do |f| %>
    .... fields
<% end %>

有什么方法可以做到这一点? 谢谢!

【问题讨论】:

  • 为什么会导致错误?你得到什么错误?
  • 在视图中,如果我使用@remote 变量设置表单remote: @remote 没有值,并且如果我使用remote: remote 我在新视图中出现错误
  • 只需给它起一个不同的名字......remote_toggle: true 然后在你的部分中调用data: { remote: remote_toggle }
  • 是不是因为你没有从新的远程传递远程本地变量是未定义的?
  • 看起来像这样。我一会儿试试。

标签: ruby-on-rails ajax


【解决方案1】:

您可以将request 作为Ajax 发送到模态框,并在form 中使用remote: request.xhr?,这样您就可以将表单用于Ajax 和非Ajax 调用。

&lt;a href="#" class="btn btn-warning btn-sm" data-remote="true" data-toggle="modal" data-target="#modalAddPatient"&gt;Add new patient&lt;/a&gt;

在形式上

#form

<%= simple_form_for @patient, remote: request.xhr? do |f| %>
    .... fields
<% end %>

如果requestAjax request,则request.xhr? 返回true,否则返回false。所以 Ajax 调用是 remote: true,非 Ajax 调用是 remote: false

更新:

好的。不知何故,上述方法对您不起作用。试试下面的方法

在调用局部变量时定义一个局部变量

<%= render partial: 'patients/form', locals: {patient: @patient, modal: true} %>

在形式上

<% modal ||= false %>
<% remote = modal ? true : false %>
<%= simple_form_for @patient, remote: remote do |f| %>
    .... fields
<% end %>

【讨论】:

  • 它不工作。在表单上,​​request.xhr? 为空。
  • @HMihail 你把链接改成我的了吗?
  • 是的,我把数据遥控器放在了链接里。
  • @HMihail 可以贴一下点击链接时生成的日志吗?
  • 上面写着:Started GET "/appointments/new?clinic_id=2&amp;physician_id=17" for 127.0.0.1 at 2016-02-18 13:39:28 +0200 Processing by AppointmentsController#new as JS
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 2019-12-25
相关资源
最近更新 更多