如何获取多态类到相关类的关联

问题描述 投票:0回答:1

我正在尝试让一些多态关联正常工作,但我无法让它们正确。目前他们给我的是两个表匹配的 ID,而不是直接关系。

class User < ApplicationRecord
  belongs_to :origin, polymorphic: true
  has_one :customer, foreign_key: :id, primary_key: :origin_id, class_name: "Customer"
  has_one :employee, foreign_key: :id, primary_key: :origin_id, class_name: "Employee"
end

class Customer < ApplicationRecord
  has_one :user, class_name: "User", foreign_key: :origin_id
end

class Employee < ApplicationRecord
  has_one :user, class_name: "User", foreign_key: :origin_id
end

如果我这样做:

user = User.create(origin: Customer.find(1))
user.customer # => #<Customer:0x000000014a78d2c8>
# I expect that the code below to be nil but it is not
user.employee # => #<Employee:0x000000014a78d2c8>

有谁知道我怎样才能获得适当的关联?预先感谢。

ruby-on-rails ruby activerecord polymorphic-associations
1个回答
0
投票

在导轨指南中有一个示例,具有

has_many
多态关联

has_one
有几乎相同的代码:

class User < ApplicationRecord
  belongs_to :origin, polymorphic: true
end

class Customer < ApplicationRecord
  has_one :user, as: :origin
end

class Employee < ApplicationRecord
  has_one :user, as: :origin
end

您需要这样的架构迁移:

create_table :users do |t| # or change_table if it is existing table
  t.belongs_to :origin, polymorphic: true # origin_id and origin_type columns
end

输出应该是这样的

user = User.create(origin: Customer.find(1))
user.customer # => #<Customer:0x000000014a78d2c8>
user.employee # => nil
© www.soinside.com 2019 - 2024. All rights reserved.