高效的 Join 查询 - 可以使用 ActiveRecord 来完成吗
我有 4 个模型,A、B、C 和 D
class A < ActiveRecord::Base
has_many :B
has_many :C, :through => :B
end
class B < ActiveRecord::Base
belongs_to :A
has_many :C
has_many :D, :through => :C
end
class C < ActiveRecord::Base
belongs_to :B
end
class D < ActiveRecord::Base
belongs_to :C
end
我有一个非常幼稚的实现,非常明显......
<% A.B.each do |b| %>
<%= b.number %>
<% b.C.each do |c| %>
<%= c.name %>
<% end %>
<% end %>
获得 A 的所有 C 的最佳方法是什么? 为 A 获得 All D 的最佳方式是什么?
我想使用带有“created_at”值的 order_by 子句来获取所有“C”,而不是迭代 B。
可能是我错过了一些 ActiveRecord 魔法?
我很感激任何帮助。
I have 4 models, A, B, C and D
class A < ActiveRecord::Base
has_many :B
has_many :C, :through => :B
end
class B < ActiveRecord::Base
belongs_to :A
has_many :C
has_many :D, :through => :C
end
class C < ActiveRecord::Base
belongs_to :B
end
class D < ActiveRecord::Base
belongs_to :C
end
I have a very naive implementation which is very obvious ...
<% A.B.each do |b| %>
<%= b.number %>
<% b.C.each do |c| %>
<%= c.name %>
<% end %>
<% end %>
What's the best way to get All C for A?
What's the best way get All D for A?
I want to get all 'C' using order_by clause with "created_at" value instead of iterating through B.
May be I'm missing some ActiveRecord magic?
I appreciate any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您需要进行一些更改。
C 类
需要与D
关联如果您想访问
A
的D
,您也需要指定这一点。现在,要访问
A
的所有C
:请注意,当您调用
aC
时,另一个查询不会被执行。这是因为 ActiveRecord 知道您想要通过include
调用访问找到的A
的C
,并生成最小数量的查询。D
也是如此:假设您想要所有
A
的D
,但想要C
ordered:请注意,您还可以将其设置为关联的默认值:
First of all, you need to make a couple changes.
class C
needs an association toD
If you want to access
A
'sD
's, you need to specify this as well.Now, to access all of
A
'sC
's:Notice how another query is not executed when you call
a.C
. This is because ActiveRecord knows you will want to access the foundA
'sC
's by theinclude
call, and generates the minimum number of queries. Same goes forD
's:Say you wanted all
A
'sD
's but wantedC
's ordered:Note you can also set this as a default on the association: