arel,如何加入

Jan*_*Jan 9 ruby ruby-on-rails arel ruby-on-rails-3

特定

class Category < ActiveRecord::Base
  has_many :products, :order => 'name ASC'
end
Run Code Online (Sandbox Code Playgroud)

使用Rails 3堆栈,如何查询"拥有"产品的所有类别?

Snu*_*ggs 30

在ARel(非ActiveRecord)中,我们将执行以下操作:

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.
Run Code Online (Sandbox Code Playgroud)

  • 在所有这些示例中,我从未看到将AREL查询折叠回Rails以获得真实记录的最后一步.现在怎么办p?您可以在其上调用to_sql,但是如何将其转换为将加载记录的ActiveRecord :: Relation? (29认同)
  • 以上是一个连接,不能卡在where方法中. (9认同)

ger*_*tas 14

Category.joins(:products).select("distinct categories.*").all
Run Code Online (Sandbox Code Playgroud)