我正在尝试使用selectize-rails
宝石。如何使用选择性从全表中进行选择?
以下代码允许我多选“Option1”和“Option2”。
视图/用户/ show.html.erb :
$('#select-to').selectize({
persist: false,
maxItems: null,
valueField: 'email',
labelField: 'name',
searchField: ['name', 'email'],
options: [
{email: 'option1@example.com', name: 'Option1'},
{email: 'option2@example.com', name: 'Option2'},
],
render: {
item: function(item, escape) {
return '<div>' +
(item.name ? '<span class="name">' + escape(item.name) + '</span>' : '') +
(item.email ? '<span class="email">' + escape(item.email) + '</span>' : '') +
'</div>';
},
option: function(item, escape) {
var label = item.name || item.email;
var caption = item.name ? item.email : null;
return '<div>' +
'<span class="label">' + escape(label) + '</span>' +
(caption ? '<span class="caption">' + escape(caption) + '</span>' : '') +
'</div>';
}
},
createFilter: function(input) {
var match, regex;
// email@address.com
regex = new RegExp('^' + REGEX_EMAIL + '$', 'i');
match = input.match(regex);
if (match) return !this.options.hasOwnProperty(match[0]);
// name <email@address.com>
regex = new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i');
match = input.match(regex);
if (match) return !this.options.hasOwnProperty(match[2]);
return false;
},
create: function(input) {
if ((new RegExp('^' + REGEX_EMAIL + '$', 'i')).test(input)) {
return {email: input};
}
var match = input.match(new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i'));
if (match) {
return {
email : match[2],
name : $.trim(match[1])
};
}
alert('Invalid email address.');
return false;
}
});
如何从完整的表格中进行选择?例如,我有一个名为“User”的表。如何从User.all
中选择,而不仅仅是预设选项?
schema.rb :
create_table "things", force: true do |t|
t.string "name"
t.string "email"
#...
end
答案 0 :(得分:1)
根据docs,您需要创建一个load
方法,该方法将使用选项数组调用callback
。将preload设置为true会强制在创建select时填充它。
在.selectize()中:
load: function(query, callback) {
$.ajax({
url: 'http://railshost/users.json',
type: 'GET',
dataType: 'json',
data: {
// query: query // if your data source allows
},
error: function() {
callback();
},
success: function(response) {
callback(response.table);
}
});
}
...
class UsersController < ApplicationController
def index
@users = User.all.where(type: "A")
respond_to do |format|
format.json { render json: @users}
end
end
end
答案 1 :(得分:1)
由于它只有大约100个对象,我认为你不需要在选择代码中搞乱;你可以简单地用Rails动态设置选项,而选择会使它们看起来很漂亮。
以下是我在我的应用中使用的方法,为您调整:
<select id='select-to'>
<option value="">Please select an option</option>
<% User.where(type: "A").each do |user| %>
<option value="<%= user.id %>"><%= user.name %></option>
<% end %>
</select>
然后选择#select-to。