如何为Rails Active Record查询编写两个内连接

时间:2015-09-29 11:09:20

标签: ruby-on-rails rails-activerecord

我想为此SQL查询编写rails活动记录查询:

SELECT c.name FROM categories as c where c.id IN (select c.parent_id FROM categories as c join categories_coaches as cc on c.id=cc.category_id where cc.coach_id=17 group by c.parent_id)

型号:

class Category < ActiveRecord::Base
  has_and_belongs_to_many :coaches
end

class Coach < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

3 个答案:

答案 0 :(得分:1)

其他解决方案建议使用数组操作,这不是一个好主意。

您实际上不需要分组和子查询。通过将查询重写为以下形式可以获得相同的结果:

SELECT categories.* FROM categories 
INNER JOIN categories c2 ON c2.parent_id = categories.id
INNER JOIN categories_coaches cc ON c2.id = cc.category_id
WHERE cc.coach_id = 17

以这种方式转换为ActiveRecord

Category.joins('INNER JOIN categories c2 ON c2.parent_id=categories.id')
        .joins('INNER  JOIN categories_coaches cc ON c2.id = cc.category_id')
        .where('cc.coach_id = ?', 17)

答案 1 :(得分:1)

嘿以这种方式尝试

categories = Category.where(:id => Category.joins(:coaches).where("coaches.id = ?", 17).group(:parent_id).map(&:parent_id))

答案 2 :(得分:0)

我不确定,但试试这个:

items = Category.joins(:coaches).where("caoches.coach_id = ?", 17).group(:parent_id).pluck(:parent_id)
categories = Category.where (id: items)