如何将另一个属性附加到 collection_select?

How to append another attribute to collection_select?

我正在尝试将布尔属性 (third_party) 添加到我当前的 collection_select,目前只显示名称:

<div class='form-group'>
  <%= f.label :project_component_id, class: "form-label" %>
  <%= f.collection_select :project_component_id, issue.project.project_components.order("LOWER(name)"), :id, :name, {include_blank:true}, class: "form-control input-sm" %>
</div>

如何附加 third_party 以便每个 select 选项都显示为 "name(third_party)"?

谢谢!

您可以在您的模型中创建一个实例方法,它用额外的文本插入您需要的属性,并将其作为第四个选项传递给您的 collection_select 助手:

我假设称为 ProjectComponent,所以:

class ProjectComponent < ApplicationRecord

def name_with_thirdparty
  "#{name}(#{third_party})"
end

所以在您看来:

<%= f.collection_select(
      :project_component_id, 
      issue.project.project_components.order("LOWER(name)"),
      :id,
      :name_with_thirdparty,
      { include_blank: true },
      class: 'form-control input-sm') %>