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:
This is my JobsResource table records:
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})
This is what you need:
Job.joins(:resource_type).where('resource_types.id = ?', 2).load
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With