【问题标题】:Show parent in label of select option在选择选项的标签中显示父级
【发布时间】:2018-04-13 12:14:49
【问题描述】:

我有一个选择框

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

并且这个选择框绑定了select2

目前,当我搜索任何内容时,会显示如下结果:-

但我想要显示搜索结果和显示项目父级的标签(注意:- 类别有一个父级。一个类别有很多子级)

但是我尝试使用option_groups,但问题是我无法选择 option_group(它是父级),但我想选择所有类别。

类别模型

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

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 能否添加category模型定义?
  • @MrShemek 嗨,请查看更新的问题,它通常是自我关联的类别。

标签: ruby-on-rails jquery-select2 simple-form


【解决方案1】:

你能试试这样的吗:

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

这应该会在选择的选项中为您提供有关父级的信息。我已经测试过了,但没有jquery-select2。

然后,您可能必须使用一些 CSS/JS/HTML 将 in ... 移动到另一行。请看here。

编辑

据我注意到jquery-select2 在选项文本中进行搜索,因此我的解决方案无法按预期工作。

例如:如果您有一个“Ferrari in Cars”选项并输入Cars,它将显示Cars 是父类别的所有选项。如果您想避免这种情况,您可以更改匹配结果的方式:doc

【讨论】:

  • 感谢您的回答,我可以在选项的文本部分添加一些 CSS,如下所示:-&lt;option value="456"&gt;computers &lt;p color="#f3f3f3"&gt;in Hardware&lt;/p&gt;&lt;/option&gt; 基本上我想在文本颜色 in ... 部分添加一些更改。我试过了,但似乎没有用。
  • 我不确定简单的&lt;p color&gt; 是否可行。我认为您必须使用templateResult 和templateSelection 选项(described here)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2019-05-28
  • 2019-06-23
  • 1970-01-01
  • 2014-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多