gpt4 book ai didi

ruby-on-rails - rails : Many to many relation to self

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:50 24 4
gpt4 key购买 nike

我在创建此关联时遇到问题:考虑模型“Entry”。我希望条目有很多条目作为 parent ,我希望条目有很多条目作为 child 。我想通过一个我称之为“关联”的模型来实现这种关系,所以这是我尝试过的:

迁移:

class CreateAssociations < ActiveRecord::Migration[5.0]
def change
create_table :associations do |t|
t.integer :parent_id
t.integer :child_id
end
end
end

关联模型:

class Association < ApplicationRecord
belongs_to :parent, class_name: 'Entry'
belongs_to :child, class_name: 'Entry'
end

到目前为止它有效。但是现在我如何使用它来创建模型到自身的两个多对多关系?

class Entry < ApplicationRecord
# has many parent entries of type entry via table associations and child_id
# has many child entries of type entry via table associations and parent_id
end

最佳答案

这应该有效:

class Entry < ApplicationRecord
has_and_belongs_to_many :parents, class_name: 'Entry', join_table: :associations, foreign_key: :child_id, association_foreign_key: :parent_id
has_and_belongs_to_many :children, class_name: 'Entry', join_table: :associations, foreign_key: :parent_id, association_foreign_key: :child_id
end

关于ruby-on-rails - rails : Many to many relation to self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com