[英]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?
怎么做?
I don't know how you could do this without writing some SQL, but this is how I would have done it: 我不知道如何在不编写一些SQL的情况下做到这一点,但这就是我应该做的:
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) 编辑:添加.references(请参阅下面的评论)
c = Category.first 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. 它将仅列出那些具有关联的worker和team_leaders的服务。
试试这个查询
Service.joins(:team_leaders, :workers).where('team_leaders.id is not null or workers.id is not null')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.