【问题标题】:how to create a scope of elements not yet in many to many relationship?如何创建尚未处于多对多关系的元素范围?
【发布时间】:2015-08-23 00:16:50
【问题描述】:

我使用 has_many :through 连接表创建了“多对多”关系。

class ProductType < ActiveRecord::Base
  has_many :assemblies
  has_many :components, through: :assemblies
end

class Assembly < ActiveRecord::Base
  belongs_to :product_type
  belongs_to :component
end

class Component < ActiveRecord::Base
  has_many :assemblies
  has_many :product_types, through: :assemblies
end

从完整的组件列表中,我可以选择一些并将它们添加到 product_type 但我应该只被允许添加一次,所以要添加的组件列表应该只显示尚未添加的组件。

我目前正在使用它 1) 已经添加的组件列表

@product_type.components

2) 尚未添加的列表

Component.all - @product_type.components

这可行,但是,我想在组件模型上创建一个范围,以便类似

@product_type.components.addable

将生成尚未添加的组件的第二个列表。

这可能吗?如果是,组件模型上的代码是什么?还是会进入 ProductType? (我还没有找到任何有效的方法) 另外,这个尚未添加的组件列表是否有名称?会是“右外连接”吗?如果不是,那是什么?

谢谢

【问题讨论】:

    标签: ruby-on-rails-4 arel


    【解决方案1】:

    这绝对是可能的。下面是一个 sn-p,它显示了应该添加到组件模型中的范围

    scope :addable_to_product_type, -> (product_type) { joins("LEFT JOIN assemblies ON assemblies.component_id = components.id AND assemblies.product_type_id = #{product_type.id}").where("assemblies.component_id IS NULL") }
    

    用法是这样的:

    Component.addable_to_product_type(@product_type)
    

    【讨论】:

    • 感谢您的快速回复。我试过了,但我得到这个错误 SQLite3::SQLException: ambiguous column name: assembly.product_type_id:
    • 我怀疑您仍在使用产品类型对象上的组件关系。由于您正在寻找没有程序集的组件,因此 Component.addable 比 @product_type.components.addable 更可取
    • 没错,但可添加的组件是每个 product_type 的。不是通用的。每个 product_type 都有一个已添加组件的列表和它自己的可添加组件的个人列表。如果我做一个 Component.addable,那会给我一个尚未在任何 product_type 上的组件列表。
    • 是的,这似乎奏效了!谢谢。如果你不介意我问一些事情。 1) 不可能按照我的意愿去做 (@product_type.components.addable) 吗? 2)这是阿雷尔吗? 3)我假设这是一个常见的操作,它有名字吗?我无法找到使用我给出的任何描述搜索的解决方案。谢谢!
    • 1.不幸的是,在给定的 product_type 上使用组件关联是行不通的,因为 rails 对这些使用 INNER JOIN 并且会返回与产品类型关联的组件。因此,即使在范围查询中使用表别名也会导致不希望的(和意外的)结果。 2. 如果您指的是 arel gem,那么没有。这些只是 vanilla rails 的语法和方法。 3. 我不确定是否有更具体的名称,除了可能是独占左连接。
    猜你喜欢
    • 2013-04-08
    • 1970-01-01
    • 2021-09-06
    • 2012-05-10
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多