Ruby on rails Rails 5:多个双向活动记录关联
我还没有找到一个能准确回答这个问题的问题。我有一个用户表和一个人表。用户有一个人代表用户的个人详细信息。然而,一个用户也可能有几个人与之关联 想想类似macOS联系人应用程序的东西。macOS用户在联系人列表中有一个联系人,其中包含用户的个人详细信息。用户还拥有多个代表其他人的联系人 用户有一个外键Ruby on rails Rails 5:多个双向活动记录关联,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我还没有找到一个能准确回答这个问题的问题。我有一个用户表和一个人表。用户有一个人代表用户的个人详细信息。然而,一个用户也可能有几个人与之关联 想想类似macOS联系人应用程序的东西。macOS用户在联系人列表中有一个联系人,其中包含用户的个人详细信息。用户还拥有多个代表其他人的联系人 用户有一个外键person\u id,该外键指向用户的个人详细信息 Person有一个外键所有者id,指向拥有该占位符Person的用户。代表用户的人的所有者id为空 好的,我创建了两个模型: class User
person\u id
,该外键指向用户的个人详细信息
Person有一个外键所有者id
,指向拥有该占位符Person的用户。代表用户的人的所有者id为空
好的,我创建了两个模型:
class User < ApplicationRecord
belongs_to :person
has_many :people, foreign_key: :owner_id
end
class Person < ApplicationRecord
has_one :user
belongs_to :user, foreign_key: :owner_id
end
我试着插入的reverse\u来更明确地定义关联,但这没有帮助。唯一有效的方法就是从Person类中删除关联。这很好,但我真的试图理解我想说的和Rails想说的之间的脱节
更新
添加迁移:
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users, id: false do |t|
t.primary_key :id, :uuid
t.string :username, null: false, unique: true
t.uuid :person_id, null: false
...
t.timestamps
end
end
end
class CreatePeople < ActiveRecord::Migration[5.0]
def change
create_table :people, id: false do |t|
t.primary_key :id, :uuid
t.uuid :owner_id
...
t.timestamps
end
add_foreign_key :people, :users, column: :owner_id, on_delete: :restrict
add_foreign_key :users, :people, column: :person_id, on_delete: :restrict
end
end
class CreateUsers
答复
雅各布·瓦努斯得到了答案。我需要更改协会的名称,如下所示:
class User < ApplicationRecord
belongs_to :person, class_name: 'Person', foreign_key: :person_id
has_many :contacts, class_name: 'Person', foreign_key: :owner_id
end
class Person < ApplicationRecord
has_one :user, class_name: 'User', foreign_key: :person_id
belongs_to :owner, class_name: 'User', foreign_key: :owner_id
end
class用户
我认为问题在于您试图将两个关系命名为同一事物。尝试重命名两个类中的所有权关系
class User < ApplicationRecord
belongs_to :person
has_many :owners, foreign_key: :owner_id, class: "Person"
end
我在尝试探索哪种关系是哪种关系时遇到困难,因此您可能需要调整此关系以适合您的数据模型。您可以发布迁移或schema.rb吗?使用迁移更新。啊,很有趣。我将尝试重构它,看看是否能让它正常工作。我真的没有想到协会的名字。关联应该是这样工作的:用户通过用户中的person_id属于一个人,并且用户有许多联系人(与“owner”相反)。Person有一个用户(与user中的“Person”相反),Person通过owner\u id亲自属于所有者。是的,就是这样。谢谢!我用有效的代码更新了我的原始问题。
class User < ApplicationRecord
belongs_to :person
has_many :owners, foreign_key: :owner_id, class: "Person"
end
class Person < ApplicationRecord
has_one :user
belongs_to :owner, foreign_key: :owner_id, class: "Person"
end