Reputation: 1936
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
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
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
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