2016-07-31 3 views
0

は、私はこれを持っている:プリント二つの値(Railsのフォーム)

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

これは私の材料名を表示します。 例:

Cat 
Cat 

ただし、材料の名前が同じであるため、これは役に立ちません。 Materialレコードには、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"] 

それは同じ値で、二回出力します。私は近いと思う?助けてください。

答えて

0

collection_selectの代わりに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, # 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 

:(あなたのコード内のメソッドsomethingに相当)メソッド:name_with_initialは次のように説明されています。