Rails 5 ask_as_taggable with select2

我们两清 提交于 2019-12-02 19:35:36

问题


I cannot see the effect of select2 in rails 5 form whether it's a text_field or select. does anyone know why the tag_list is not being populated. I can see that the tag_list has values but as you see in the snap below, it shows "No results found". Does select2 work with Rails 5 as I've tried several options?

form: Select all will display all values into the box

<%= 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

I made the text field simple instead of select2 and was able to add tags in DB by adding :tag_list to strong params.

application.js -

Note: select2 didnot work o I used select2-full which I saw somewhere in Google.

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

JS code for select2

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

});

Now, I checked with normal HTML & JS it even worked with select2(or 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 

And the corresponding JS code is:

$("#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");
}

});

Can someone point out if normal HTML select-input works with select2 why does it not have same functionality in rails 5? I tried with both bootstrap_form_for and form_for. I even read about turbolinks issue...how to tackle the issue with turbolinks not loading the select2?


回答1:


I solved it by changing text-field to select:

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

JS code is:

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

});

and yes, do add a file called Tag.rb in app/models. The gem only installs tables but doesn't create model.

class Tag < ApplicationRecord
   validates_presence_of :name
end


来源:https://stackoverflow.com/questions/43877283/rails-5-ask-as-taggable-with-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!