在 ActiveRecord 查询中为表名添加类名

问题描述 投票:0回答:1

我有这条线:

factory.workers.where.not(confirmed_at:nil).where(job_roles: {heavy_lifting:true, sensitive_area: false}).pluck(:work_capacity)

但是关联表

job_roles
取决于工厂的类名,我有5种类型的工厂。因此,如果
factory.class.name == "DistributionCenter"
那么
job_roles
实际上将是
distribution_center_roles
,或者如果
factory.class.name == "AutomotiveAssemblyPlant"
那么
job_roles
将是
automotive_assembly_plant_roles
等等。

有没有办法在ActiveRecord查询代码中的关联表名称中子类名,这样它就不会说

job_roles
,而是说
distribution_center_roles
automotive_assembly_plant_roles
(等等),基于类名
factory

liiiiike

factory.workers.where.not(confirmed_at:nil).where((factory.class.name + "_roles").string_to_tablename_rails_method: {heavy_lifting:true, sensitive_area: false}).pluck(:work_capacity)

或者我必须这样做:

if factory.is_a?(DistributionCenter)
  factory.workers.where.not(confirmed_at:nil).where(distribution_center_roles: {heavy_lifting:true, sensitive_area: false}).pluck(:work_capacity)
elsif factory.is_a?(AutomotiveAssemblyPlant)
  factory.workers.where.not(confirmed_at:nil).where(automotive_assembly_plant_roles: {heavy_lifting:true, sensitive_area: false}).pluck(:work_capacity)
etc
ruby-on-rails class activerecord
1个回答
0
投票

您可以使用

ActiveRecord::Base::table_name

job_roles_table_name = :"#{factory.class.table_name}_roles"

factory.workers.where.not(confirmed_at:nil).where(job_roles_table_name => {heavy_lifting:true, sensitive_area: false}).pluck(:work_capacity)
© www.soinside.com 2019 - 2024. All rights reserved.