相关疑难解决方法(0)

如何通过has_many关系显示唯一记录?

我想知道在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
Run Code Online (Sandbox Code Playgroud)

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

他们可能多次订购了一些产品,所以我使用counter_cache以降序排序,根据订单数量显示.

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

@products = @user.products.ranked(:limit => 10).uniq!
Run Code Online (Sandbox Code Playgroud)

当产品有多个订单记录时有效,但如果产品只订购一次,则会产生错误.(排名是在别处定义的自定义排序函数)

另一种选择是:

@products = @user.products.ranked(:limit => 10, :select => "DISTINCT(ID)")
Run Code Online (Sandbox Code Playgroud)

我不相信我在这里采取了正确的方法.

有没有其他人解决这个问题?你遇到了什么问题?我在哪里可以找到更多关于.unique之间的区别!和DISTINCT()?

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

谢谢

ruby-on-rails unique distinct ruby-on-rails-3

101
推荐指数
5
解决办法
4万
查看次数

标签 统计

distinct ×1

ruby-on-rails ×1

ruby-on-rails-3 ×1

unique ×1