【问题标题】:Perform a join on two Rails models implementing single table inheritence在两个实现单表继承的 Rails 模型上执行连接
【发布时间】:2020-01-26 22:20:04
【问题描述】:

我有三个模型,我们称它们为ProductTemplateProductReadyProduct。这些只有一个表,products 表,TemplateProductReadyProduct 都继承自 Product 模型。 TemplateProductReadyProduct 之间存在 has_many/belongs_to 关联。模板用于布置产品的一般特征,Readys 用于定制产品以及实际可供客户查看的内容。每个TemplateProduct 都有一个id,每个ReadyProduct 都有一个与其模板相关联的template_product_id

该项目是使用 Rails 5 构建的。

我想要做的是收集TemplateProducts 的列表,然后获取与ReadyProducts 关联的每个模板的计数,并以不会破坏数据库的方式这样做。我了解 ActiveRecord 关联,但我的 SQL 很弱,而且我对联接的了解有限。我可以用一个简单的Product.where(conditions 收集TemplateProducts 的列表,但我不知道一旦我有了这个。为了灵活性起见,我希望能够将我的ReadyProduct 计数从这个初始集合中计算出来,因为有时我需要额外的计数,有时我不需要。我确信一定有一个简单的方法可以做到这一点,但我还没有找到解决方案。

【问题讨论】:

    标签: ruby-on-rails ruby join single-table-inheritance


    【解决方案1】:

    如果您只需要 TemplateProduct ids 到 ReadyProduct 计数的映射,那么您只需要:

    TemplateProduct.joins(:ready_products).group(:id).count
    

    如果您希望 TemplateProduct 实例中包含 ReadyProduct 计数,那么您将需要这个:

    tps = TemplateProduct.joins(:ready_products).select('products.*, COUNT(ready_products_products.id) ready_product_count').group(:id)
    
    tps.first.ready_product_count
    #=> 6
    

    ready_products_products 由 Rails 定义,它在实际表名 (products) 前加上模型名称的“表形式”(复数、蛇形、小写、ready_products),并用下划线连接。

    【讨论】:

    • 如果您想要结果中没有 ReadyProjects 的 TemplateProjects,请使用 .left_joins
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多