无法急切加载多态关联:item

时间:2019-05-24 15:38:23

标签: ruby-on-rails postgresql activerecord

我需要获取@client的所有帐户(has_many :accounts, as: :item是关系)。拥有一个具有:item多态字段(belongs_to :item, polymorphic: true,仅此而已)的Account模型,具有has_many :accountsbelongs_to :client的Sale模型。

我的查询是: @accounts = Account.where(company: current_user.company_id).joins(:items).where({ items: { client_id: @client.id } })

,并收到以下错误: Cannot eagerly load the polymorphic association :item

class Sale < ApplicationRecord
  belongs_to :user
  belongs_to :company
  belongs_to :category, required: false
  belongs_to :client, required: false
  has_many :accounts, as: :item
end

class Client < ApplicationRecord
  belongs_to :user
  belongs_to :company
  belongs_to :category, required: false
  has_many :sales
end

class Account < ApplicationRecord
  belongs_to :item, polymorphic: true
  belongs_to :user
  belongs_to :company
end

我希望带有所有@client付款的Account对象的输出。

1 个答案:

答案 0 :(得分:2)

或者,这可以通过将其分为两个查询来帮助您获得预期的结果:-

sales_ids_for_client = @client.sales.pluck(:id)
accounts_of_given_client = Account.where("item_type = ? AND item_id IN (?)", 'Sale', sales_ids_for_client)