2

假设我有一个这样的模型:

class Animal
    include DataMapper::Resource
    property :id, Serial
    property :type, Enum[ :cat, :bat, :rabbit, :zebra]
end

假设有一条路线指向 erb 模板以添加更多动物,@animal = session[:animal]我将如何创建动物类型列表?

...
<form>
  <% @animal.type.each do |animal| %>
    <select>
      <option value="<%= @animal.type" %></option>
    </select>
  <% end %> 
</form>

(显然那段代码并不能满足我的要求,但我希望它能让它更清楚一点。)

4

1 回答 1

3

属性上有 flags 选项,可用于查找枚举值。我不知道这是在哪里记录的 - 我在这里找到了。所以你可以做这样的事情:

<form>
  <select>
    <% Animal.type.options[:flags].each do |animal| %>
      <option value="<%= animal %>"><%= animal %></option>
    <% end %>
  </select>
</form>

我想您可以将其概括为辅助方法。

于 2011-10-04T11:46:50.363 回答