【发布时间】: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