【问题标题】:Query empty polymorphic associations查询空的多态关联
【发布时间】:2018-10-31 14:14:00
【问题描述】:

我正在尝试查找所有没有Bar 关联的Foo。我知道这不起作用,但类似于Foo.where(barable: nil)

Foo 模型

class Foo < ApplicationRecord
    has_many :bars, as: :barable
end

条形模型

class Bar < ApplicationRecord
    belongs_to :barable, polymorphic: true
end

表格

Foo(id: integer, name: string, created_at: datetime, updated_at: datetime)

Bar(id: integer, barable_type: string, barable_id: string, created_at: datetime, updated_at: datetime)

【问题讨论】:

  • 您好 ferne97,请查看this answer,这应该会有所帮助
  • 您的示例没有反映真正的多态用例,这隐藏了这里的复杂性。您还需要一个Baz,即barable,这暴露了问题——您不能像查询普通的has-many/belongs-to关系那样查询连接表id是否为空,因为您不知道连接表名而不询问 Rails 类。

标签: ruby-on-rails ruby ruby-on-rails-5


【解决方案1】:
Foo.joins('LEFT JOIN bars ON bars.foo_id = foos.id').where('bars.id is null') 

【讨论】:

  • left_outer_joins 似乎不适用于多态关联
  • 没错,我换了另一种方式。这应该适用于多态关联。 @ferne97
  • 在他的示例中,bars 上没有 foo_id。如果有的话,这将是一种拥有很多/属于的关系,而不是在Bar 上具有barable_idbarable_type 的多态关系,而在任何其他模型上都没有。
猜你喜欢
  • 2011-03-20
  • 2010-10-15
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多