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)
ger*_*tas 14
Category.joins(:products).select("distinct categories.*").all
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15207 次 |
| 最近记录: |