【问题标题】:Rails 5 ask_as_taggable with select2带有 select2 的 Rails 5 ask_as_taggable
【发布时间】:2017-10-08 04:55:51
【问题描述】:

无论是 text_field 还是 select,我都无法在 rails 5 表单中看到 select2 的效果。有谁知道为什么 tag_list 没有被填充。我可以看到 tag_list 有值,但正如您在下面的快照中看到的那样,它显示“未找到结果”。 select2 是否可以与 Rails 5 一起使用,因为我已经尝试了几个选项?

form: Select all 将所有值显示到框中

<%= f.label :tags, "Tags (separated by commas)" %>
<%= f.text_field :tag_list, value: f.object.tag_list.each { |e| e} %>
<input type="checkbox" id="checkbox" >Select All

我使文本字段变得简单而不是 select2,并且能够通过将 :tag_list 添加到强参数来在 DB 中添加标签。

application.js -

注意:select2 不起作用,我使用了我在 Google 某处看到的 select2-full。

//= require underscore
//= require select2-full

select2 的 JS 代码

$(function() {
$('input#post_tag_list').select2({tags:[], placeholder: "Choose a Tag", allowClear: true})

});

现在,我检查了普通的 HTML 和 JS,它甚至可以与 select2(或 select2-full)一起使用

<select multiple id="e1" style="width:300px">
   <option value="A">Apple</option>
   <option value="B">Banana</option>
   <option value="G">Grapes</option>
  </select>

  <input type="checkbox" id="checkbox" >Select All 

而对应的JS代码为:

$("#checkbox").click(function(){
if($("#checkbox").is(':checked') ){
  $("#post_topic_list > option").prop("selected","selected");
  $("#post_topic_list").trigger("change");
}else{
  $("#post_topic_list > option").removeAttr("selected");
  $("#post_topic_list").trigger("change");
}

});

有人能指出普通的 HTML 选择输入是否适用于 select2,为什么它在 rails 5 中没有相同的功能?我尝试了 bootstrap_form_for 和 form_for。我什至阅读了有关 turbolinks 问题...如何解决 turbolinks 未加载 select2 的问题?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 jquery-select2 select2-rails


    【解决方案1】:

    我通过将文本字段更改为选择来解决它:

    <%= f.select(:tag_list, Tag.all.order(:name).collect { |a| [a.name, a.id]}, {}, id: "tag_list", label:'Tags', :multiple => true)%>
    

    JS代码是:

    $(function() {
    $("#tag_list" ).select2();
    

    });

    是的,在 app/models 中添加一个名为 Tag.rb 的文件。 gem 只安装表,不创建模型。

    class Tag < ApplicationRecord
       validates_presence_of :name
    end
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 2017-01-13
      • 2018-06-20
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多