仅检索关联的记录

时间:2014-07-25 10:52:07

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

我需要找出至少与任何一条记录相关联的记录。

我有这种关系:

Class Category < ActiveRecord::Base
  has_many :services
end

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

我只需要找出那些至少有一个工作人员或一个团队负责人与之关联的服务。怎么做?

3 个答案:

答案 0 :(得分:1)

我不知道如何在不写一些SQL的情况下做到这一点,但我就是这样做的:

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

修改:添加.references(请参阅下面的评论)

答案 1 :(得分:1)

c = Category.first

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

它将仅列出那些具有关联工人和team_leaders的服务。

答案 2 :(得分:0)

尝试此查询

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