ruby-on-rails - Rails 6 has_one through 和多态关联
问题描述
我有以下模型关系:
class Wallet < ApplicationRecord
belongs_to :walletable, polymorphic: true
end
class SpvSetup < ApplicationRecord
belongs_to :portfolio
has_one :wallet, as: :walletable
end
class User < ApplicationRecord
has_one :wallet, as: :walletable
end
因为SpvSetup
belongs_toPortfolio
我想通过模型访问Portfolio
模型,以便能够执行以下操作:Wallet
SpvSetup
wallet = Wallet.last
wallet.portfolio
为此,我已更新Wallet
并Portfolio
建模如下:
class Wallet < ApplicationRecord
belongs_to :walletable, polymorphic: true
has_one :portfolio, through: :spv_setup, source: :walletable, source_type: 'Wallet'
end
class Portfolio < ApplicationRecord
has_one :spv_setup, dependent: :destroy
has_many :wallet, through: :spv_setup, source: :walletable, source_type: 'Wallet'
end
但我得到的只是一个错误:
> wallet.portfolio
ActiveRecord::HasManyThroughAssociationNotFoundError (Could not find the association :spv_setup in model Wallet)
Did you mean? walletable
transactions
fake_wallet
解决方案
我相信你可以使用delegate
你想要达到的目标。例如:
class Wallet < ApplicationRecord
belongs_to :walletable, polymorphic: true
delegate :portfolio, to: :spv_setup
end
class SpvSetup < ApplicationRecord
belongs_to :portfolio
has_one :wallet, as: :walletable
end
以上将让你做到:
wallet = Wallet.last
wallet.portfolio
有关更多信息,请查看此
希望这有帮助。
推荐阅读
- java - websphere 启动时 ibm 文件监控出错
- c# - 如何获取具有本地时间信息的 DateTimeOffset
- sql - 如何将具有特定标签的数据组织到新列中?
- c# - 比较两个数据集 A 和 B 并仅在 A 中返回数据
- javascript - 在传入要用作回调的函数时使用jQuery时对“this”感到困惑
- django - Django 创建和更新视图:外键字段
- c# - DateTime.AddHours 给出错误的输出和日期时间格式更改
- ios - 在 objc_object::release() 中崩溃
- java - 在java中实现以对象为参数的方法
- vector - 二进制补码向量 VHDL 的左移