SkRoR
SkRoR

Reputation: 1199

How to filter records from association

How to get records from association? I have 4 jobs in my jobs table.How to filter all jobs with resource_type_id=2. From the below records here for eg (I want to get job id with 2 and 3 as result).

Here is my association

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

This is my how resources_type table is saved:

enter image description here

This is my JobsResource table records:

enter image description here

Upvotes: 4

Views: 2047

Answers (3)

Giridharan
Giridharan

Reputation: 568

You can retrieve Job records with a resource_types record associated with:

Job.joins(:resource_types)

if you need all resource_types records which don't have an association with job you can execute:

ResourceType.where(job: nil)

Upvotes: 0

Abolfazl Mahmoodi
Abolfazl Mahmoodi

Reputation: 390

This is what you need:

Job.joins(:resource_type).where('resource_types.id = ?', 2).load

Upvotes: 1

Vishal
Vishal

Reputation: 7361

You can do it in below ways

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})

Upvotes: 7

Related Questions