我在想,在Rails3中,从一个has_many, through关系中展示唯一的记录的最佳方法是什么。
我有三个模型:
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!
如果一个产品有多个订单记录,则此功能有效,但如果该产品仅被订购一次,则会生成错误。(ranked是在其他地方定义的自定义排序函数)
另一种选择是:
@products = @user.products.ranked(:limit => 10, :select => "DISTINCT(ID)")
我不太确定我的做法是否正确。
有没有其他人尝试过这个?你遇到了什么问题?我在哪里可以找到关于 .unique! 和 DISTINCT() 之间的区别的更多信息?
通过 has_many, through 关系生成一个唯一记录列表的最佳方法是什么?
谢谢。
has_many :products, :through => :orders, :uniq => true
已经被废弃。现在,你应该这样写:has_many :products, -> { uniq }, through: :orders
。 - Kurt MuellerDISTINCT
和ORDER BY
子句时发生冲突,您可以始终使用has_many :products, -> { unscope(:order).distinct }, through: :orders
。 - fagianihas_many :subscribed_locations, -> { unscope(:order).select("DISTINCT ON (locations.id) locations.*") },through: :people_publication_subscription_locations, class_name: 'Location', source: :location
,否则你将会出现rails ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: could not identify an equality operator for type json
的错误。 - ryan2johnson9