2

Say I have a model like so:

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

Assuming there is a route pointing to an erb template for adding more animals & @animal = session[:animal] how would I create a list of animal types?

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

(Obviously that bit of code doesn't do what I am looking for, but I hope it makes it a little more clear.)

Don Graziano
  • 431
  • 5
  • 15

1 Answers1

3

There is flags option on the property that you can use to lookup the enum values. I don't know where this is documented - I found it here. So you could do something like this:

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

I guess you could generalise this into a helper method.

animuson
  • 50,765
  • 27
  • 132
  • 142
Steve
  • 14,938
  • 3
  • 42
  • 39
  • Oh thats beautiful man! _Exactly_ what I was looking for. Strange that this is not better documented 0o. I don't quite get how one would make this into a helper method though... – Don Graziano Oct 04 '11 at 14:47
  • It might be worth making this into a helper method if it helps keep your views clean and simple especially if you are going to be using this pattern in more than one place. Sinatra doesn't come with a whole load of built-in view helpers like rails but they are simple to write, e.g. http://www.sinatrarb.com/faq.html#helpview – Steve Oct 05 '11 at 11:44