如何在sinatra视图中列出可能的枚举符号?

时间:2011-10-04 01:47:10

标签: ruby sinatra datamapper ruby-datamapper

说我有这样的模型:

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>

(显然,一些代码并不能满足我的要求,但我希望它能让它更加清晰。)

1 个答案:

答案 0 :(得分:3)

属性上有flags选项,可用于查找枚举值。我不知道这在哪里记录 - 我发现它here。所以你可以这样做:

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

我猜你可以将它概括为辅助方法。