如何通过关系显示has_many中的唯一记录? [英] How to display unique records from a has_many through relationship?
问题描述
我想知道通过Rails3中的关系显示has_many中唯一记录的最佳方法是什么。
I'm wondering what is the best way to display unique records from a has_many, through relationship in Rails3.
我有三种模型:
class User < ActiveRecord::Base
has_many :orders
has_many :products, :through => :orders
end
class Products < ActiveRecord::Base
has_many :orders
has_many :users, :through => :orders
end
class Order < ActiveRecord::Base
belongs_to :user, :counter_cache => true
belongs_to :product, :counter_cache => true
end
说我想列出客户订购的所有产品显示页面。
Lets say I want to list all the products a customer has ordered on their show page.
他们可能已经多次订购某些产品,所以我使用counter_cache根据订单数以降序显示。
They may have ordered some products multiple times, so I'm using counter_cache to display in descending rank order, based on the number of orders.
但是,如果他们多次订购产品,我需要确保每个产品仅列出一次。
But, if they have ordered a product multiple times, I need to ensure that each product is only listed once.
@products = @user.products.ranked(:limit => 10).uniq!
在有多个订单记录的情况下有效,但如果仅购买了一个产品,则会产生错误订购一次。 (排名是在其他位置定义的自定义排序功能)
works when there are multiple order records for a product, but generates an error if a product has only been ordered once. (ranked is custom sort function defined elsewhere)
另一种替代方法是:
@products = @user.products.ranked(:limit => 10, :select => "DISTINCT(ID)")
我不确定在这里采用正确的方法。
I'm not confident that I'm on the right approach here.
还有其他人解决吗?您遇到了什么问题?在哪里可以找到有关.unique之间差异的更多信息!和DISTINCT()?
Has anyone else tackled this? What issues did you come up against? Where can I find out more about the difference between .unique! and DISTINCT()?
通过has_many通过关系生成唯一记录列表的最佳方法是什么?
What is the best way to generate a list of unique records through a has_many, through relationship?
谢谢
推荐答案
您是否尝试在has_many关联上指定:uniq选项:
Have you tried to specify the :uniq option on the has_many association:
has_many :products, :through => :orders, :uniq => true
来自 Rails文档:
:uniq
如果为true,则将从集合中省略重复项。与:through一起使用。
If true, duplicates will be omitted from the collection. Useful in conjunction with :through.
更新铁路4:
在Rails 4中, has_many:products,:through => :orders,:uniq => true
已弃用。相反,您现在应该编写 has_many:products,->。 {独特},通过::orders
。请参阅 distinct部分,以获取has_many :: ActiveRecordAssociations文档上的关系以获取更多信息。感谢Kurt Mueller在他的评论中指出了这一点。
In Rails 4, has_many :products, :through => :orders, :uniq => true
is deprecated. Instead, you should now write has_many :products, -> { distinct }, through: :orders
. See the distinct section for has_many: :through relationships on the ActiveRecord Associations documentation for more information. Thanks to Kurt Mueller for pointing this out in his comment.
这篇关于如何通过关系显示has_many中的唯一记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!