问题描述
我有一个结构是这样的:
I have a structure something like this:
class User
has_many :dongles
has_many :licences, :through => :dongles
end
class Dongle
has_many :licences
belongs_to :user
end
class Licence
belongs_to :dongle
end
然而,时间的推移,用户最终获取多份许可证的每个加密狗。合理的应用程序要总结最近的牌照为每个。
However, time passes and the user eventually gets multiple licences for each dongle. Reasonably, the app wants to summarise the most recent licences for each.
我知道我能天真地做到这一点是这样的:
I know I can naively do it like this:
user.dongles.each do |dongle|
licence = dongle.licences.find(:first, :order => 'created_at DESC')
# do something with the licence info
end
但是,有没有办法通过收集来做到这一点,避免大的数目通常会做它用简单的方式?
But is there a way to do this through the collection and avoid the large number of queries which would normally result by doing it the naive way?
我尝试这样做:
user.licences.find(:all, :order => 'created_at DESC', :group => 'dongle_id')
这不会返回一个许可证为每个软件狗,但它需要第一个被'身份证',的没有的由我在查询中指定的顺序。
This does return one licence for each dongle, but the first one it takes is decided by 'id', not by the order I have specified in the query.
有没有一种方法可以让我得到它给我的第一个每个,使用排序顺序我提供判断哪个是第一?
Is there a way I can get it to give me the first of each, using a sort order I provide to decide which is the first?
推荐答案
从你的模型中,所有关联信息已经被宣布。实际上,你可以使用每个用户访问加密狗,并执行与ActiveRecord的单个查询许可信息的包括的选项。
From your models, all association info has already been declared. You can actually use each of user to access dongles and licences info by performing a single query with ActiveRecord include options.
# Say the table name is licences and dongles.
users = User.find(:all,
:include => [:dongles, :licences],
:order => "licences.created_at DESC, dongles.created_at DESC")
我假设你要创建的每个用户所拥有的每一个加密狗的最新许可证的摘要。您可能会削减在您的实际需要循环。
I assume you want to create a summary of latest licence of each dongle owned by each user. You may cut the loop upon your actual needs.
users.each do |user|
# do something with your user info
user.dongles.each do |dongle|
# do something with your dongle info
licence = dongle.licences.first
# do something with the licence info
end
end
了解更多关于这在 http://snippets.dzone.com/posts/show/2089
这篇关于Rails的活动记录:在会同发现:为了和:组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!