Shnarf
Shnarf

Reputation: 39

How to append another attribute to collection_select?

I am trying to add a boolean attribute (third_party) to my current collection_select that currently just shows name:

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

How would I append third_party so that each select option is shown as "name(third_party)"?

Thanks!

Upvotes: 1

Views: 131

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33481

You can create an instance method in your model which interpolates the attribute you need with the extra text and pass it as the fourth option to your collection_select helper:

I assume is called ProjectComponent, so:

class ProjectComponent < ApplicationRecord

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

So in your view:

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

Upvotes: 3

Related Questions