Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 330
SreRoR Avatar asked Sep 16 '25 03:09

SreRoR


2 Answers

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})
like image 72
Vishal Avatar answered Sep 19 '25 13:09

Vishal


This is what you need:

Job.joins(:resource_type).where('resource_types.id = ?', 2).load
like image 32
Abolfazl Mahmoodi Avatar answered Sep 19 '25 14:09

Abolfazl Mahmoodi