首页 > 解决方案 > Rails如何使用join在另一个表中仅查找具有关联的has_one对象的对象

问题描述

嗨,我有一个模型 UnpairedProduct,我需要编写一个范围,仅显示未通过表名 feed_product 关联的 PairedProduct 的 UnpairedProducts。我尝试使用下面的代码执行此操作并收到此错误:NoMethodError: undefined method `table_name' for nil:NilClass

我还尝试了其他写作选项,不幸的是没有成功。你知道如何正确写吗?

未配对产品型号:

class UnpairedProduct < ApplicationRecord
  belongs_to :feed_product

  scope :resolved, -> { joins(feed_product: :paired_product).distinct.count }
  scope :not_resolved, -> { joins(:feed_product).where.missing(:paired_product) } # PROBLEM HERE, THIS IS NOT WORKING

end

饲料产品型号

class FeedProduct < ApplicationRecord
  has_many :unpaired_products
  has_one :paired_product
end

配对产品型号

class PairedProduct < ApplicationRecord
  belongs_to :feed_product
end

标签: ruby-on-railsjoinscopemodel-associations

解决方案


推荐阅读