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

如何从关联中筛选记录

  •  1
  • SkRoR  · 技术社区  · 6 年前

    如何从关联中获取记录。 我的作业表中有4个作业。如何筛选资源类型为2的所有作业。从下面的记录中,例如(我想要得到2和3的工作ID)。

    这是我的协会

    class Job < ActiveRecord::Base   
      has_many :jobs_resources   
      has_many :resource_type, through: :jobs_resources, dependent: :destroy   
    end
    
    class ResourceType < ActiveRecord::Base   
      has_many :jobs_resources   
      has_many :jobs, through: :jobs_resources, dependent: :destroy end
    
    class JobsResource < ActiveRecord::Base   
      belongs_to :job   
      belongs_to :resource_type 
    end
    

    这是我保存资源类型表的方式

    enter image description here

    这是我的工作来源表记录 enter image description here

    请帮忙。任何帮助都是值得感激的。

    3 回复  |  直到 6 年前
        1
  •  4
  •   Vishal    6 年前

    你可以用下面的方法

    Job.includes(:resource_type).where(resource_types: {id: 2}) 
    
    Job.includes(:jobs_resources).where(jobs_resources: {resource_type_id: 2}) 
    
    Job.joins(:jobs_resources).where(jobs_resources: {resource_type_id: 2})
    
        2
  •  1
  •   Abolfazl Mahmoodi    6 年前

    这就是你需要的:

    Job.joins(:resource_type).where('resource_types.id = ?', 2).load
    
        3
  •  0
  •   Giridharan    6 年前

    您可以使用与以下内容相关联的资源类型记录来检索作业记录:

    Job.joins(:resource_types)
    

    如果需要与作业没有关联的所有资源类型记录,可以执行:

    ResourceType.where(job: nil)