开发者

Rails ActiveRecord Join

开发者 https://www.devze.com 2023-04-02 09:53 出处:网络
I\'m using rails and am trying to figure out how to use ActiveRecord within the method to combine the following into one query:

I'm using rails and am trying to figure out how to use ActiveRecord within the method to combine the following into one query:

def children_active(segment)
  parent_id = Category.select('id').where('segment' => segment)
  Category.where('parent_id'=>parent_id, 'active' => true)
end

Basically, I'm trying to get sub categories of a category that is designated by a unique column called segment. Right now, I'm getting the id of the category in the first query, and then using that value for the parent_id in the second query. I've been trying to figure out how to use AR to do a join so that it can be a开发者_Python百科ccomplished in just one query.


You can use self join with a alias table name:

Category.joins("LEFT OUTER JOIN categories AS segment_categories on segment_categories.id = categories.parent_id").where("segment_categories.segment = ?", segment).where("categories.active = ?", true)

This may looks not so cool, but it can implement the query in one line, and there will be much less performance loss than your solution when data collection is big, because "INCLUDE IN" is much more slower than "JOIN".

0

精彩评论

暂无评论...
验证码 换一张
取 消