假设我有一个像这样的模型:
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>
(显然,这段代码并不能满足我的要求,但我希望它能让它更加清晰。)
最佳答案
属性上有标志选项,您可以使用它来查找枚举值。我不知道这是在哪里记录的 - 我找到了它 here 。所以你可以这样做:
<form>
<select>
<% Animal.type.options[:flags].each do |animal| %>
<option value="<%= animal %>"><%= animal %></option>
<% end %>
</select>
</form>
我想你可以将其概括为一个辅助方法。
关于ruby - 如何在 sinatra View 中列出可能的枚举符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7642517/