在collection_select中打印两个值(Rails表单)

时间:2016-07-31 16:13:24

标签: ruby-on-rails ruby forms collection-select

对于我的表格,我有这个:

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

这会打印我的材料名称。 例如:

Cat 
Cat

但是,这没有用,因为这些材料具有相同的名称。 材质记录中还有另一个属性:color。

我希望它在下拉列表中打印出来

Cat - Brown
Cat - Orange

我该怎么做呢?我试着调用一个方法,但它没有打印出我想要的方式。这就是我所做的。

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

然而,下拉列表打印出来如下:

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

它打印两次,具有相同的值。我想我很亲密?请帮忙。

2 个答案:

答案 0 :(得分:0)

如果您使用select代替collection_select,我认为会更容易。试试吧:

<%= tag_field.select :id, Material.order(:name).map{ |m| [ "#{m.name} - #{m. color}", m.id ] }, {prompt: "-select-"} %>

答案 1 :(得分:0)

This answer清楚地解释了 collection_select 帮助器的用法。方法:name_with_initial(对应于代码中的方法something)解释为:

: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

因此,如果您获得两次结果,则意味着集合/数组具有冗余值。