使用 Rails STI 模型和连接条件
Use Rails STI model with join conditions
我定义了以下模型:
class Group < ActiveRecord::Base
end
class Person < ActiveRecord::Base
end
class Policeman < Person
end
class Firefighter < Person
end
里面Group
,我想得到所有有Policemen
的组,例如:
class Group < ActiveRecord::Base
has_many :policemen
scope :with_policemen, -> { joins(:policemen).uniq }
end
这按预期工作。现在,如果我想获取所有具有 Policeman
和 status: 3
的组,我会这样做:
class Group < ActiveRecord::Base
has_many :policemen
scope :with_policemen, -> { joins(:policemen).where(policemen: { status: 3 }).uniq }
end
但不幸的是,这不起作用,因为 ActiveRecord 使用 policemen
table 构造查询,这显然不存在。一种解决方案是在范围内使用 where(people: { status: 3 })
,但我想知道为什么 ActiveRecord 不能在 WHERE 子句中放置正确的 table,因为它具有必要的关联集。
根据 the docs,哈希语法的预期格式为 table_name: { column_name: val }
。
scope :with_policemen, -> { joins(:policemen).where(people: { status: 3 }).uniq }
我同意你的看法 - 如果 where 和 join 语法相似的话会更有意义。另一个不一致之处 - group
方法不采用散列,只采用字符串或数组。
我定义了以下模型:
class Group < ActiveRecord::Base
end
class Person < ActiveRecord::Base
end
class Policeman < Person
end
class Firefighter < Person
end
里面Group
,我想得到所有有Policemen
的组,例如:
class Group < ActiveRecord::Base
has_many :policemen
scope :with_policemen, -> { joins(:policemen).uniq }
end
这按预期工作。现在,如果我想获取所有具有 Policeman
和 status: 3
的组,我会这样做:
class Group < ActiveRecord::Base
has_many :policemen
scope :with_policemen, -> { joins(:policemen).where(policemen: { status: 3 }).uniq }
end
但不幸的是,这不起作用,因为 ActiveRecord 使用 policemen
table 构造查询,这显然不存在。一种解决方案是在范围内使用 where(people: { status: 3 })
,但我想知道为什么 ActiveRecord 不能在 WHERE 子句中放置正确的 table,因为它具有必要的关联集。
根据 the docs,哈希语法的预期格式为 table_name: { column_name: val }
。
scope :with_policemen, -> { joins(:policemen).where(people: { status: 3 }).uniq }
我同意你的看法 - 如果 where 和 join 语法相似的话会更有意义。另一个不一致之处 - group
方法不采用散列,只采用字符串或数组。