gpt4 book ai didi

ruby-on-rails - 如何通过关系显示 has_many 中的唯一记录?

转载 作者:行者123 更新时间:2023-12-03 04:47:14 24 4
gpt4 key购买 nike

我想知道通过 Rails3 中的关系显示 has_many 中唯一记录的最佳方式是什么。

我有三个模型:

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

假设我想列出客户在其展示页面上订购的所有产品。

他们可能多次订购了某些产品,因此我使用 counter_cache 根据订单数量按降序显示。

但是,如果他们多次订购产品,我需要确保每个产品仅列出一次。

@products = @user.products.ranked(:limit => 10).uniq!

当产品有多个订单记录时有效,但如果产品仅订购过一次,则会生成错误。 (排名是在其他地方定义的自定义排序函数)

另一种选择是:

@products = @user.products.ranked(:limit => 10, :select => "DISTINCT(ID)")

我不确定我的方法是否正确。

还有其他人解决过这个问题吗?您遇到了什么问题?我在哪里可以找到有关 .unique! 之间区别的更多信息。和 DISTINCT()?

通过 has_many 和关系生成唯一记录列表的最佳方法是什么?

谢谢

最佳答案

您是否尝试在 has_many 关联上指定 :uniq 选项:

has_many :products, :through => :orders, :uniq => true

来自the Rails documentation :

:uniq

If true, duplicates will be omitted from the collection. Useful in conjunction with :through.

RAILS 4 更新:

在 Rails 4 中,has_many :products, :through => :orders, :uniq => true 已弃用。相反,您现在应该编写 has_many :products, -> {distinct }, through: :orders。请参阅distinct section for has_many: :through relationships on the ActiveRecord Associations documentation了解更多信息。感谢 Kurt Mueller 在评论中指出了这一点。

关于ruby-on-rails - 如何通过关系显示 has_many 中的唯一记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5846638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com