Ahmad hamza
Ahmad hamza

Reputation: 1936

Retrieve only associated records

I need to find out the records which are at least associated to any one of the records.

I've this relationship:

Class Category < ActiveRecord::Base
  has_many :services
end

Class Service < ActiveRecord::Base
  has_many :team_leaders, through: :allocations
  has_many :workers, through: :allocations
end

I need to find out only those services which has at least one worker or one teamleader associated to it. How to do it?

Upvotes: 0

Views: 63

Answers (3)

ex0ns
ex0ns

Reputation: 1116

I don't know how you could do this without writing some SQL, but this is how I would have done it:

Service.includes(:team_leaders, :workers).where('team_leaders.id is not null OR workers.id is not null').references(:team_leaders, :workers).all

Edit: adding .references (see comments below)

Upvotes: 1

Priti Bankar
Priti Bankar

Reputation: 11

c = Category.first

c.services.each do |service|
 if Allocation.exists?(:service_id => service.id)
   puts service.name
   puts service.service_name
 end
end

It will list only those services which has associated workers and team_leaders.

Upvotes: 1

nsave
nsave

Reputation: 984

Try this query

Service.joins(:team_leaders, :workers).where('team_leaders.id is not null or workers.id is not null')

Upvotes: 0

Related Questions