views:

95

answers:

2
+1  Q: 

arel, how to join

Given

class Category < ActiveRecord::Base
  has_many :products, :order => 'name ASC'
end

Using the Rails 3 stack, how can I query for all categories that 'have' products?

+2  A: 

Category.joins(:products).select("distinct categories.*").all

gertas
That worked, cool thanks.
Jan Limpens
Do you happen to know a good reference on what is possible with arel queries?
Jan Limpens
I take my knowledge from googling, reading Rails-elite blogs. Important thing: ActiveRecord differs much from pure Arel.
gertas
+2  A: 

In ARel (NOT ActiveRecord) we will do the following:

p = Arel::Table.new :products    # Base Rel-var
c = Arel::Table.new :categories  # Base Rel-var

predicate = p[:category_id].eq( c[:id] ) # for equality predicate

p.join(c)                   # Natural join
  .on( predicate )          # Equi-Join
  .group( p[:category_id] ) # Grouping expression to get distinct categories
  .project( c[:id] )        # Project the distinct category IDs of the derived set.
Snuggs