代码之家  ›  专栏  ›  技术社区  ›  Tintin81

如何用一个查询访问两个多态关联?

  •  0
  • Tintin81  · 技术社区  · 5 年前

    在我的Rails 6应用程序中,我有以下模型:

    class Account < ApplicationRecord
    
      has_many :carriers
      has_many :clients
    
      # Unfortunately, these two don't work together. I have to uncomment one of them to get the other one to work:
      has_many :people, :through => :carriers # works but omits clients
      has_many :people, :through => :clients # works but omits carriers
    
    end
    

    class Carrier < ApplicationRecord
    
      belongs_to :account
    
      has_many :people, :as => :personalizable
    
    end
    

    class Client < ApplicationRecord
      
      belongs_to :account
    
      has_many :people, :as => :personalizable
    
    end
    

    class Person < ApplicationRecord
    
      belongs_to :personalizable, :polymorphic => true
    
    end
    

    如何访问帐户的 carriers clients 在一个查询中?

    我很想做一些像 account.people 但目前还没有找到实现这一目标的方法。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Ravi Teja Gadi    5 年前

    不能对两个关联使用相同的方法名,而可以将其重命名为 carrier_people client_people

    class Account < ApplicationRecord
    
      has_many :carriers
      has_many :clients
    
      has_many :carrier_people, :through => :carriers, source: :people # works but omits clients
      has_many :client_people, :through => :clients, source: :people # works but omits carriers
    
    end
    

    你可以这样装。

    Account.includes(:carrier_people, :client_people)