minlingzhao minlingzhao - 4 months ago 11
Ruby Question

print two values in collection_select (Rails Forms)

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.

Answer

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-"} %>