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

时间:2018-04-14 18:16:55

标签: ruby-on-rails 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以便每个选择选项显示为&#34; name(third_party)&#34;?

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以在模型中创建一个实例方法,使用额外的文本插入所需的属性,并将其作为第四个选项传递给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') %>