如何为关联has_many实现动态class_name?对于同一个表,不同的引擎

时间:2016-04-07 10:13:08

标签: ruby-on-rails ruby associations

请告诉我如何实现动态关联链接的方式,动态关联链接本身由属性模型决定。 我有两个引擎(Tbitcoin,Tstripe),每个都有一个表支付。模型User具有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动态确定引擎的方法是什么?

1 个答案:

答案 0 :(得分:0)

I think that you need a regular method instead of has_many association which will find proper payments associated with the user according to pay_currency value. Example:

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