How do I so a select input for a STI column in a Rails model?
- by James A. Rosen
I have a model with single-table inheritance on the type column:
class Pet < ActiveRecord::Base
TYPES = [Dog, Cat, Hamster]
validates_presence_of :name
end
I want to offer a <select> dropdown on the new and edit pages:
<% form_for @model do |f| %>
<%= f.label :name %>
<%= f.text_input :name %>
<%= f.label :type %>
<%= f.select :type, Pet::TYPES.map { |t| [t.human_name, t.to_s] } %>
<% end %>
That gives me the following error:
ActionView::TemplateError (wrong argument type String (expected Module))
I read a suggestion to use an alias for the field #type since Ruby considers that a reserved word that's the same as #class. I tried both
class Pet < ActiveRecord::Base
...
alias_attribute :klass, :type
end
and
class Pet < ActiveRecord::Base
...
def klass
self.type
end
def klass=(k)
self.type = k
end
end
Neither worked. Any suggestions? Oddly, it works fine on my machine (MRI 1.8.6 on RVM), but fails on the staging server (MRI 1.8.7 not on RVM).