在 ActiveRecord 中建立分叉关系模型
Model a fork relationship within ActiveRecord
对于引用自身的 class,ActiveRecord::Migration 和 ActiveRecord::Base 看起来像什么。我正在为一个对象建模,该对象 "forks" 与现有记录无关,并将该关系存储在 :source 字段中。该 :source 字段将包含 primary_key :id 它的父项。
ActiveRecord 不包含这种类型的 "predefined" 关系,但您可以使用 has_many
和 belongs_to
帮助程序自己定义它。您需要添加一个外键,例如my_parent_id
到模型(我称之为 Thing
):
rails g migration AddMyParentIdToThings my_parent:references
然后您需要定义指定外键和 class 名称的关系:
class Thing < ActiveRecord::Base
belongs_to :parent_thing, class_name: "Thing", foreign_key: :my_parent_id
has_many :child_things, class_name: "Thing", foreign_key: :my_parent_id
end
如果外键与关系名称匹配,则可以省略 belongs_to
上的 :foreign_key
选项( 而不是 has_many
)附加的 "_id"
例如:
belongs_to :my_parent, class_name: "Thing"
当我不得不做类似的事情时,我喜欢将其视为一个链接到自身的模型。
在您的迁移文件中,您只需将 parent_id
as as as integer 添加到那个 table/model
class Category < ActiveRecord::Base
belongs_to :parent, :class_name => "Category", :foreign_key => :parent_id
has_many :children, :class_name => "Category", :foreign_key => :parent_id
end
对于引用自身的 class,ActiveRecord::Migration 和 ActiveRecord::Base 看起来像什么。我正在为一个对象建模,该对象 "forks" 与现有记录无关,并将该关系存储在 :source 字段中。该 :source 字段将包含 primary_key :id 它的父项。
ActiveRecord 不包含这种类型的 "predefined" 关系,但您可以使用 has_many
和 belongs_to
帮助程序自己定义它。您需要添加一个外键,例如my_parent_id
到模型(我称之为 Thing
):
rails g migration AddMyParentIdToThings my_parent:references
然后您需要定义指定外键和 class 名称的关系:
class Thing < ActiveRecord::Base
belongs_to :parent_thing, class_name: "Thing", foreign_key: :my_parent_id
has_many :child_things, class_name: "Thing", foreign_key: :my_parent_id
end
如果外键与关系名称匹配,则可以省略 belongs_to
上的 :foreign_key
选项( 而不是 has_many
)附加的 "_id"
例如:
belongs_to :my_parent, class_name: "Thing"
当我不得不做类似的事情时,我喜欢将其视为一个链接到自身的模型。
在您的迁移文件中,您只需将 parent_id
as as as integer 添加到那个 table/model
class Category < ActiveRecord::Base
belongs_to :parent, :class_name => "Category", :foreign_key => :parent_id
has_many :children, :class_name => "Category", :foreign_key => :parent_id
end