1

I have one select box

<%=simple_form_for order_item do |oi|%>
  <%= order_item.association :category, label: false, collection: current_company.categories, placeholder: 'Category', input_html: { class: 'form-control form-control-sm drop_down_input order_item_category} %>
<%end%>

and this select box is bind with select2

currently, when I search anything this shows results like this: -

enter image description here

But I want to results like show search and with a label that showing item's parent (note: - category has one parent. and one category has many children)

enter image description here

however I tried with option_groups with this the issue is I cant select option_group(which is parent), but I want to select all category.

Category model

belongs_to :parent, class: 'category', foreign_key: 'parent_id'
has_many :children, class: 'category'

Any help would be appreciated. thanks.

Community
  • 1
  • 1
Anand
  • 6,457
  • 3
  • 12
  • 26

1 Answers1

1

Can you please try with something like this:

<%= order_item.association :category, collection: current_company.categories.collect { |c| [ c.id, "#{c.name} in #{c.parent.name}" ] }, value_method: :first, label_method: :last, placeholder: 'Category', input_html: { class: 'form-control form-control-sm drop_down_input order_item_category} %>

This should give you an information about parent in the select's option. I have tested it but without jquery-select2.

Then, you will probably have to use some CSS/JS/HTML to move in ... to another line. Please take a look here.

Edit

As far as I noticed jquery-select2 searches in the option's text, so my solution will not work as expected.

For instance: if you have a "Ferrari in Cars" option and you type Cars it will display all options where Cars is a parent category. If this is something that you would like to avoid, you can change the way of matching results: doc

MrShemek
  • 2,413
  • 1
  • 16
  • 20
  • thanks for your answer can i add some css on text part of option like this: - `` basically i wanted to add some change in text colour `in ...` part. i tried to but doesnt seem to work. – Anand Apr 14 '18 at 08:21
  • I am not sure if simple `

    ` will work. I think you have to use `templateResult` and `templateSelection` options ([described here](https://stackoverflow.com/a/34324334/2039726))

    – MrShemek Apr 14 '18 at 15:28