首页
/ Chosen for Rails Asset Pipeline 技术文档

Chosen for Rails Asset Pipeline 技术文档

2024-12-26 09:46:54作者:韦蓉瑛

1. 安装指南

1.1 安装 chosen-rails gem

首先,在 Rails 项目的 Gemfile 中添加 chosen-rails gem:

gem 'jquery-rails'
gem 'chosen-rails'

然后运行以下命令安装依赖:

bundle install

1.2 关于 jQuery

你可以通过 jquery-rails gem 获取 jQuery。如果你在 Rails 4 及以上版本中遇到 Turbolinks 问题,建议使用 jquery-turbolinks

2. 项目的使用说明

2.1 引入 Chosen 的 JavaScript 资源

app/assets/javascripts/application.js 文件中添加以下内容,以使用 jQuery 版本的 Chosen:

//= require jquery
//= require chosen-jquery

如果你使用 Prototype,可以添加以下内容:

//= require jquery
//= require chosen-prototype

2.2 引入 Chosen 的样式表资源

app/assets/stylesheets/application.css 文件中添加以下内容:

*= require chosen

2.3 启用 Chosen JavaScript

在 Rails 6 中,确保在 app/views/layouts/application.html.erb 文件中添加 javascript_include_tag

<%= javascript_include_tag 'application' %>

然后,在某个 CoffeeScript 文件中(例如 scaffold.js.coffee)添加以下代码以启用 Chosen:

$ ->
  # enable chosen js
  $('.chosen-select').chosen
    allow_single_deselect: true
    no_results_text: 'No results matched'
    width: '200px'

注意:从 Chosen 0.9.15 开始,width 选项是必需的。

确保该文件在 application.js 中被引入:

//= require chosen-jquery
//= require scaffold

2.4 在表单中使用 Chosen

在表单字段中添加 chosen-select 类:

<%= f.select :author,
  User.all.map { |u| [u.name, u.id] },
               { include_blank: true },
               { class: 'chosen-select' }
%>

如果你使用 Simple Form 作为表单构建器:

<%= f.association :author,
                  collection: User.all,
                  include_blank: true,
                  input_html: { class: 'chosen-select' }
%>

3. 项目 API 使用文档

3.1 RSpec 辅助方法

chosen-rails 提供了 RSpec 功能辅助方法,允许用户从单选框或多选框中选择或取消选择选项。在 spec/rails_helper.rb(或 spec/spec_helper.rb)中添加以下内容:

require 'chosen-rails/rspec'

这将自动配置 RSpec,添加以下内容:

RSpec.configure do |config|
  config.include Chosen::Rspec::FeatureHelpers, type: :feature
end

配置包括两个额外的辅助方法,适用于所有 type: :feature 的测试:

chosen_select(value, options = {})
chosen_unselect(value, options = {})

这两个方法都需要在 options 哈希中包含 from: '...',它可以是 CSS 选择器或字段的标签(需要标签上有 for 属性)。

3.2 示例用法

处理单选框:

chosen_select('Leo Tolstoy', from: 'Author')
chosen_unselect('Leo Tolstoy', from: '#author')
chosen_select('Fyodor Dostoyevsky', from: '#author')

处理多选框:

chosen_select('Leo Tolstoy', 'Fyodor Dostoyevsky', 'Anton Chekhov', from: 'Authors')
# 或者,单个值:
chosen_select('Leo Tolstoy', from: '#authors')

chosen_unselect('Fyodor Dostoyevsky', ' Anton Chekhov', from: 'Authors')
# 或者,单个值:
chosen_unselect('Leo Tolstoy', from: '#authors')

4. 项目安装方式

4.1 更新 Chosen 源文件

使用以下 Rake 命令更新 Chosen 源文件:

rake update-chosen

4.2 发布 gem

使用以下 Rake 命令发布 gem:

rake release

5. 许可证

chosen-rails gem 使用 MIT 许可证。

登录后查看全文
热门项目推荐