我有这条线:
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
莉莉克
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