代码之家  ›  专栏  ›  技术社区  ›  daveasdf_2

在ActiveRecord查询中为表名子类名称

  •  0
  • daveasdf_2  · 技术社区  · 2 年前

    我有这样一句话:

    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 汽车装配工厂道路 (等等),基于的类名 factory ?

    像liiiike

    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
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   mechnicov    2 年前

    如果表的名称基于模型名称,则可以 underscore

    job_roles = :"#{factory.class.name.underscore}_roles"
    

    如果模型使用了一些名称空间,您可能还需要 parameterize

    job_roles = :"#{factory.class.name.undercore.parameterize(separator: '_')}_roles"
    

    比较

    Asdf::FooBar.name.underscore
    # => "asdf/foo_bar"
    
    Asdf::FooBar.name.underscore.parameterize(separator: '_')
    # => "asdf_foo_bar"
    

    如果表的名称基于表名,则可以 tableize

    job_roles = :"#{factory.class.name.tableize}_roles"
    

    也可以使用 ActiveRecord::Base::table_name

    即使你习惯性地重新定义,它也会起作用 table_name 在模型内部或使用自定义 table_name_prefix / table_name_suffix

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

    之后,您可以将其应用于查询

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