Ruby:启用跨 4 个模型查询的关联

Ruby: Associations to enable querying across 4 models

我整天都在尝试解决这个问题,但一无所获。我有这4个模型。 Shop Customer CreditCreditChange

我想 return CreditChanges 为商店的顾客,而不是顾客。像这样:

latest_changes = Shop.last.customers.credit_changes

我正在尝试 join 这样,但它 return 是客户而不是 credit_changes

Shop.last.customers.joins(:credit, :credit_change).where.not(credit_changes: {date: nil})

我的模型如下所示:

class Shop < ActiveRecord::Base
  has_many :customers, dependent: :destroy

class Customer < ActiveRecord::Base
  has_one :credit, dependent: :destroy
  has_many :credit_changes, through: :credit
  belongs_to :shop

class Credit < ActiveRecord::Base
  belongs_to :customer
  has_many :credit_changes, dependent: :destroy

class CreditChange < ActiveRecord::Base
  belongs_to :credit

我哪里错了?

尝试反转你看待事物的方式:

CreditChange.joins(:credit => :customer).where(customers: {shop: Shop.last}).where.not(credit_changes: {date: nil})

你想要 has-many-through 关系。

一家商店通过它的客户有很多 CreditChanges。

尝试:

class Shop
  has_many :customers
  has_many :credit_changes, through: :customers
end

@shop.credit_changes

您可以在 Rails 文档中阅读更多内容 https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association