Jeff Jeff - 4 months ago 13
Ruby Question

How to create custom label in 'options_from_collection_for_select' method?

I would like to modify what the user sees in a drop down given a collection. Instead of just the "product" field being visible, I would like it to be something like "Vender Product, version" or something like that.

Can this be done with the 'options_from_collection_for_select' method?

I have a Ruby on Rails view with this line in it (slim):

select.form-control#external_tool_question_external_tool name="external_tool_question[external_tool]"
= options_from_collection_for_select(@external_tools, :id, "product")


@external_tools = ExternalTool.all

Model (through a few different migrations):

t.string :value
t.string :validator
t.string :example_answer
t.boolean :required, :null => false, :default => true
t.boolean :is_file_upload, :null => false, :default => false

add_reference :external_tool_questions, :external_tool, index: true

What I've tried:


options_from_collection_for_select(@external_tools, "id", "product vendor")

(also... I can't figure out how to get the select tag to work... I'm using simple form as well... not really the pressing issue, but just a side issue)


You can alter your ExternalTool like following:

class ExternalTool
  def label
    "#{vendor} #{product} v #{version}"

When you set the variable in your controller:

class SomeController < ApplicationController
  def form_action
    @external_tools = ExternalTool.all

You can use it in your template as follow:

options_from_collection_for_select(@external_tools, "id", "label")

Take a note, that options_from_collection_for_select in his third argument accepts the name to be called. Here we're using label in ExternalTool.

Hope that helps! Good luck!