How do I so a select input for a STI column in a Rails model?

Posted by James A. Rosen on Stack Overflow See other posts from Stack Overflow or by James A. Rosen
Published on 2010-06-14T23:32:36Z Indexed on 2010/06/14 23:42 UTC
Read the original article Hit count: 317

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).

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about forms