【问题标题】:Rails form select for model with one-to-many relation with itselfRails表单选择与自身具有一对多关系的模型
【发布时间】: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

在此模型的表单中,我希望有一个 &lt;select&gt; 从现有类型(或 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 分配给唯一名称,然后将该表用作选择器的来源。
  • 当我尝试访问 &lt;p&gt;&lt;%= @type.supertype.name %&gt;&lt;/p&gt; 中的超类型并在控制台中设置 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


【解决方案1】:

belongs_tohas_many 调用需要将 :class_name 指定为 String 而不是实际的类对象(您可以选择省略 belongs_to 上的 :foreign_key) :

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

【讨论】:

  • 谢谢,就是这样:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 2014-05-16
  • 2020-10-05
  • 2016-03-14
  • 2019-07-29
相关资源
最近更新 更多