如何为协会has_many实现动态class_name?同样的table,不同的引擎

How to implement dynamic class_name for the association has_many? For the same table, different engines

请告诉我如何实现动态关联link,它本身由属性模型决定。 我有两个引擎(Tbitcoin、Tstripe),每个引擎都有 table 付款。模型用户具有 pay_currency 属性,这是管理。

class User < ActiveRecord::Base

  has_many :payments, ~> { where "pay_currency = 'real'" } , class_name: Tstripe::Payment, foreign_key: :uid
  has_many :payments, ~> { where "pay_currency = 'bitcoin'" } ,class_name: Tbitcoin::Payment, foreign_key: :uid
end

使用User.last.payments.create动态确定引擎的方法有哪些?

我认为您需要一种常规方法而不是 has_many 关联,它会根据 pay_currency 值找到与用户关联的适当付款。示例:

class User < ActiveRecord::Base
  def payments
    payment_class = case pay_currency
    when "real"
      Tstripe::Payment
    when "bitcoin"
      Tbitcoin::Payment
    end
    payment_class.for_user(self)
  end
end

class Tstripe::Payment < ActiveRecord::Base
  belongs_to :user

  def self.for_user(user)
    where(user_id: user.uid)
  end
end