【发布时间】:2015-07-24 16:47:08
【问题描述】:
我有一个 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> 从现有类型(或 nil)列表中选择它的超类型。这样做的正确方法是什么?现在我的代码看起来像这样:
<%= 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
【问题讨论】:
-
对于顶级
Type。我真的不认为 nil 是这里的问题,即使我从列表中选择合法的Type,这段代码也不会生成正确的模型。 -
您能否更具体地说明为什么它不起作用?控制器是否给出某种错误?值是否按预期发布?如果您尝试直接在控制台中分配
supertype_id,是否有效? -
您的类型名称在
types表中是唯一的吗?如果没有,您可能需要考虑一个单独的表,例如type_names,它将唯一 ID 分配给唯一名称,然后将该表用作选择器的来源。 -
当我尝试访问
<p><%= @type.supertype.name %></p>中的超类型并在控制台中设置supertype_id时,此代码会生成undefined method 'arel_table' for ActiveRecord::Type:Module并没有帮助。而且表单数据看起来像type[name]:typename type[supertype_id]:2 commit:Create Type,所以我猜没关系。 -
@lurker 是的,它们应该是独一无二的。
标签: ruby-on-rails ruby forms ruby-on-rails-4 model-view-controller