我刚刚切换到Rails 6(6.0.0.rc1),默认情况下,它将Webpacker gem与Rails UJS一起用于Javascriptassets资源 .我想在我的一些模块中使用Rails UJS,以便从具有以下功能的函数提交表单:

const form = document.querySelector("form")
Rails.fire(form, "submit")

在以前安装了Webpacker的Rails版本中,Rails参考在我的模块中似乎是"全球"可用的,但现在我在调用Rails.fire时得到了这个…

ReferenceError: Rails is not defined

How can i make 100 from 101 available to a specific or to all of my modules?

在我的设置下面…

app/javascript/controllers/form_controller.js

import { Controller } from "stimulus"

export default class extends Controller {
  // ...
  submit() {
    const form = this.element
    Rails.fire(form, "submit")
  }
  // ...
}

app/javascript/controllers.js

// Load all the controllers within this directory and all subdirectories. 
// Controller files must be named *_controller.js.

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start()
const context = require.context("controllers", true, /_controller\.js$/)
application.load(definitionsFromContext(context))

app/javascript/packs/application.js

require("@rails/ujs").start()
import "controllers"

谢谢

推荐答案

在我的app/javascript/packs/application.js句话中:

import Rails from '@rails/ujs';
Rails.start();

然后在我写的任何模块、控制器和组件中:

import Rails from '@rails/ujs';

Ruby-on-rails相关问答推荐

在has_many关系中由两个条件 Select

Data-turbo-stream=&FALSE&QOOT;不适用于带有方法POST的表单

ActiveRecord::声明在类别中无效#new

具有 IN 子句的参数化查询在 ruby​​-on-rails 的 blazer 工具中无法按预期工作

多行与内联块之间的不同行为

NoMethodError:Puma::Events:Class 的未定义方法字符串

无效的单表继承类型:Rails

Rails 3 应用程序的 MySQL 集群 (NDB) 与 MySQL 复制 (InnoDB):优点/缺点?

Rails 路由到唯一索引

如何使用 Vim 插入 ERB 标签?

如何在rails中发回js.haml

如何在where子句中组合两个条件?

使用 RSpec 2 关闭一个规范的事务性固定装置

Rails:仅当值存在时如何验证格式?

使用 oauth 和 twitter ruby​​ gem 时不断收到 OAuth::Unauthorized 错误

我们如何在 Rails Mailer 中设置邮箱发件人的名称?

在 Rails 路由中更改 id 参数

如何在 Rails 迁移中判断数据库类型?

Rails:在 link_to 中保留 GET 查询字符串参数

ActionMailer 在开发 Rails 4 中不发送邮件