我是 Rails 6 和 webpacker 的新手。我用 rails 和 webpacker 创建了一个新应用程序,一切正常,但是当我尝试使用 select2 时遇到了一个问题,我得到了 readyException.js:6 Uncaught TypeError: $(...).select2 is not a function错误并且无法将所选属性提交到数据库。我已经审查并尝试了网络上提出的几个建议,但没有奏效。不知道我哪里出错了。任何帮助深表感谢。顺便说一句,我使用的是 simple_form 和 Slim。
应用程序/资产/application.scss
@import 'bootstrap/scss/bootstrap';
应用程序/javascript/样式表/application.scss
@import 'bootstrap/scss/bootstrap';
应用程序/javascript/packs/application.js
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
import "jquery";
import "popper.js";
import "bootstrap";
import "../stylesheets/application"
import "@fortawesome/fontawesome-free/js/all"
import select2 from 'select2';
import 'select2/dist/css/select2.css';
require("@rails/activestorage").start()
require("channels")
require("jquery")
Rails.start()
Turbolinks.start()
ActiveStorage.start()
$(document).ready(function() {
$('.select').select2();
});
配置/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'
})
)
module.exports = environment
视图表单views/users/_form.html.slim
= simple_form_for [:admin, @user] do |f|
= f.error_notification
= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?
.form-inputs.form-group.center-block style="width:240px"
= f.input_field :first_name,
placeholder: 'First Name',
class: 'form-control',
autofocus: true,
required: true
.form-inputs.form-group.center-block style="width:240px"
= f.input_field :last_name,
placeholder: 'Last Name',
class: 'form-control',
autofocus: true,
required: true
.form-inputs.form-group.center-block style="width:240px"
= f.input_field :email,
placeholder: 'Email',
class: 'form-control',
autofocus: true,
required: true
.form-inputs.form-group.center-block style="width:240px"
= f.select :roles, Role.all.map { |role| role.name }, {include_blank: true, required: true,
include_hidden: false}, class: 'form-control', input_html: {class: 'select'}
.form-actions.form-group.center-block style="width:240px"
button.btn.btn-primary.space-above type="submit" Save
= link_to "Cancel", admin_users_path, class: 'btn btn-default space-left'