select2-rails + act_as_taggable_on rails 4 issue

痴心易碎 提交于 2019-12-31 07:08:10

问题


I installed select2-rails and act_as_taggable_on gem to my app. I setup the act_as_taggable_on and it works (I tested from the console). However, when I tried to create the view so that user can add new tag, it's not working.

I want to make a tagging support like this: https://select2.github.io/examples.html#tokenizer.

Here is my setup:

apps/assets/application.js

$(document).ready(function(){
  $(".multiple-input").select2({
    theme: "bootstrap";
    tags: true;
    tokenSeparators: [',']
  })
});

apps/views/profiles/new.html.erb

<%= form_for @profile, url: user_profile_path do |f| %>
  <%= f.text_field :name, placeholder: "Full Name" %>
  <%= f.text_field :skill_list, placeholder: "Skills", class: 'multiple-input' %>
<% end %>

When I open the profiles/new on my browser, the skill_list text field show as the way it is instead of using select2 tagging system.

There must be something wrong or missing with my code. Please help.

Update 1

I changed the code to:

<%= f.select :skill_list, placeholder: "Skills", class: 'multiple-input' %>

No luck.

So, I installed simple form gem because based on this article (http://onewebstory.com/notes/user-friendly-tagging-on-rails) select2 rails won't work with select tag.

Here is my current code:

apps/views/profiles/new.html.erb

<%= simple_form_for(@profile, url: user_profile_path) do |f| %>
  <div class="form-inputs" %>
    <%= f.input :name, placeholder: 'Full Name' %>
    <%= f.input :skill_list, input_html: { class: 'multiple-input' } %>
   </div>
<% end %>

apps/assets/application.js

$(document).ready(function() {
  $('input.multiple-input').each(function() {
    $(this).select2({
      theme: 'bootstrap',
      tags: $(this).data('tags'),
      tokenSeparators: [',']
      });
    });
});

The select2 is working, I can use the select2 search and dropdown. However I want it to be tagging input and every time the user inputs comma (,) temporary stored just like in here :(https://select2.github.io/examples.html#tokenizer)


回答1:


It's working now. I did it with this code: https://stackoverflow.com/a/33035355/5081949

Here is my code now:

app/views/profiles/new.html.erb

<%= f.input :skill_list, input_html: { class: 'multiple-input', multiple: "multiple" }, collection: @profile.skill_list %>

app/assets/application.js

$(document).ready(function() {
  $('.multiple-input').each(function() {
    $(this).select2({
      tags: true,
      tokenSeparators: [','],
      theme: 'bootstrap',
      placeholder: 'Separated by comma'
      });
    });
});

also in apps/controllers/profiles_controller.rb I added strong params

def profile_params
  params.require(:profile).permit(:name, skill_list: [])
end


来源:https://stackoverflow.com/questions/35762999/select2-rails-act-as-taggable-on-rails-4-issue

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