ruby - 从数据库填充时解析文本问题

时间:2012-04-28 17:50:48

标签: ruby

尝试使用数据库中的值创建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 sage放在哪里

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

你也可以这样使用collection_select

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

(我假设您尝试将成分ID分配给的父对象为:recipe。更改该值以适合您的应用。)