2016-07-31 45 views
0

對於我的形式,我有這樣的:打印兩個值(Rails的形式)

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

這將打印我的材料名稱。 示例:

Cat 
Cat 

但是,這沒有幫助,因爲材料具有相同的名稱。 「材質」記錄中還有另一個屬性:顏色。

我希望它打印出此下拉

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

它打印出兩次,相同的價值觀。我覺得我很近?請幫忙。

回答

0

我認爲如果您使用select而不是collection_select會更容易。試試看:

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

所以,如果你得到的結果兩次就意味着收集/陣列具有冗餘的值。