【问题标题】:How to append another attribute to collection_select?如何将另一个属性附加到 collection_select?
【发布时间】:2018-09-24 20:34:21
【问题描述】:

我正在尝试将布尔属性(第三方)添加到当前仅显示名称的当前 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,以便每个选择选项都显示为“name(third_party)”?

谢谢!

【问题讨论】:

    标签: ruby-on-rails collection-select


    【解决方案1】:

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

    【讨论】:

    • 应该是name + "(#{third_party})"
    • 这太棒了 - 谢谢!我只是稍微更新了一下以获得我想要的,但你明白我的目的!
    • "#{name}(#{third_party})" 工作但也谢谢你@Salil
    • 更新了答案。谢谢。
    猜你喜欢
    • 2015-01-14
    • 2011-12-26
    • 2022-07-21
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多