首页 > 解决方案 > 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我想通过模型访问Portfolio模型,以便能够执行以下操作:WalletSpvSetup

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

标签: ruby-on-rails

解决方案


我相信你可以使用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

有关更多信息,请查看

希望这有帮助。


推荐阅读