0

For my form, I have this:

<%= tag_field.collection_select( :id, Material.order(:name), :id, :name,
      :prompt => "-select-")%>

This prints my materials names. example:

Cat 
Cat

However, this is not helpful because the materials have the same names. There is another attribute in the Material record, :color.

I want it to print out this in the dropdown

Cat - Brown
Cat - Orange

How do I go about doing this? I tried calling a method instead, but it doesn't print out the way I want it to. Here's what I did.

View:     
<%= tag_field.collection_select( :id, Material.order(:name), :id, :something,
      :prompt => "-select-")%>

Model:
def something
    materials_array = []
    Material.all.each do |material|
      if material.color == nil
        material.name + '-' + material.size
      else
        materials_array.push(material.name + '-' + material.color)
      end
    end
    materials_array
  end

However, the dropdown prints out like this:

["Cat - Brown", "Cat - Orange"]
["Cat - Brown", "Cat - Orange"]

It prints out twice, with the same values. I think I'm close? Please help.

cats
  • 55
  • 7

2 Answers2

0

I think it's easier if you use select instead of collection_select. Try it:

<%= tag_field.select :id, Material.order(:name).map{ |m| [ "#{m.name} - #{m. color}", m.id ] }, {prompt: "-select-"} %>
Tan Nguyen
  • 3,281
  • 1
  • 18
  • 18
0

This answer explains clearly the usage of collection_select helper. The method :name_with_initial (which corresponds to the method something in your code) is explained as:

:name_with_initial, # this is name of method that will be called for
# every row, result will be set as value
 
# as a result, every option will be generated by the following rule: 
# <option value=#{author.id}>#{author.name_with_initial}</option>
# 'author' is an element in the collection or array

So if you are getting results twice it means the collection/array has redundant values.

Community
  • 1
  • 1
mansoor.khan
  • 2,309
  • 26
  • 39