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

因为SpvSetupbelongs_toPortfolio,我想通过SpvSetupWallet模型访问Portfolio模型,以便能够做这样的事情:

wallet = Wallet.last
wallet.portfolio

为此,我更新了WalletPortfolio模型,如下所示:

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

查看更多信息

希望有帮助。

最新更新