2012-04-28 94 views
0

填充时,文本分析问题,试图在Ruby中创建简单的下拉列表从数据库中值 - 这样的:红宝石 - 从数据库

<% ingredientArray = Ingredient.all.map { |ingredient| [ingredient.name, ingredient.id] } %> 
<div class="field"> 
    <%= select_tag(:ingredient_id, ingredientArray) %><br/> 
</div> 

,我收到了一个empy。
这是生成的html

<div class="field"> 
    <select id="ingredient_id" name="ingredient_id">[[&quot;Paprika&quot;, 5], [&quot;Cinnamon&quot;, 8], [&quot;Salt&quot;, 9], [&quot;Pepper&quot;, 10], [&quot;water&quot;, 11]]</select><br/> 
</div> 

我应该在哪里把HTML圣人

回答

2

您应该select_tag和相关方法阅读文档。 它的第二个参数是一个包含选择框选项标签的字符串。 可以手动生成:

select_tag "people", "<option>David</option>".html_safe 

或者使用options_from_collection_for_select方法吧:

select_tag "people", options_from_collection_for_select(@people, "id", "name") 

(从文档的例子)

具体来说,在你的情况做出的最好的方法下拉是:

<div class="field"> 
    <%= select_tag("Ingredients", options_from_collection_for_select(Ingredient.all, 'id', 'name')) %> 
</div> 
0

您还可以使用collection_select像这样:

<%= collection_select :recipe, :ingredient_id, Ingredient.all, :id, :name, { prompt: "&ndash; Select an Ingredient &ndash;".html_safe } %> 

(我假设你想指定成分ID来是:recipe父对象。根据您的应用更改该值。)