Borsunho
Borsunho

Reputation: 1157

Rails form select for model with one-to-many relation with itself

I have a Type model with one-to-many relation to itself, i.e.

class Type < ActiveRecord::Base
  belongs_to :supertype, class_name: Type, foreign_key: 'supertype_id'
  has_many :subtypes, class_name: Type, foreign_key: 'supertype_id'
end

In form for this model I'd like to have a <select> to choose it's supertype from list of existing Types (or nil). What would be correct way to do so? Right now my code looks like so:

<%= form_for(@type) do |f| %>
  <%= f.select(:supertype_id, ( Type.all.collect {|t| [ t.name, t.id ] }) + ["",nil] ) %>
<% end %>

but obviously that doesn't work.

In my migration I have this code, if that helps:

create_table :types do |t|
  t.string :name
  t.references :supertype, index: true, foreign_key: true

  t.timestamps null: false
end

Upvotes: 0

Views: 936

Answers (1)

eirikir
eirikir

Reputation: 3842

The belongs_to and has_many calls need to specify :class_name as a String not as the actual class object (and you can optionally omit the :foreign_key on the belongs_to):

class Type < ActiveRecord::Base
  belongs_to :supertype, class_name: "Type"
  has_many :subtypes, class_name: "Type", foreign_key: 'supertype_id'
end

Upvotes: 1

Related Questions