我有这条线:
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
如果表的名称基于型号名称,则可以直接
underscore
使用如果模型使用了某个命名空间,您可能还需要
parameterize
比较:
如果表名是基于表名的话,
tableize
可以也可以使用
ActiveRecord::Base::table_name
table_name
即使您在模型内自定义重新定义或使用自定义table_name_prefix
/,它也将起作用table_name_suffix
之后您可以将其应用到您的查询中