Rails形式选择与自身具有一对多关系的模型

时间:2015-07-24 16:47:09

标签: ruby-on-rails ruby forms ruby-on-rails-4 model-view-controller

我有一个Type模型,它与自身有一对多的关系,即

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

在此模型的表单中,我希望<select>从现有类型列表(或零)中选择它的超类型。这样做的正确方法是什么?现在我的代码看起来像这样:

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

但显然这不起作用。

在我的迁移中,我有这段代码,如果有帮助的话:

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

  t.timestamps null: false
end

1 个答案:

答案 0 :(得分:1)

belongs_tohas_many调用需要将:class_name指定为 String 而不是实际的类对象(并且您可以选择省略{{1}在:foreign_key):

belongs_to
相关问题