ruby 如何获得独特的多态关联

gcxthw6b  于 9个月前  发布在  Ruby
关注(0)|答案(3)|浏览(120)

我试图得到一个多态关系的列表,没有任何重复。
我有一个StoreViews表,它有一个名为viewable的多态字段(因此表中有一个viewable_id和viewable_type列)。现在我想显示视图,每个多态关系只显示一次,没有重复。

@views = StoreView.
    .distinct(:viewable_id)
    .distinct(:viewable_type)
    .order("created_at DESC")
    .limit(10)

字符串
因此,如果StoreViews中有两条记录,两者具有相同的可见关系,@views应该只返回最近的一条。然而,情况并非如此。

ttygqcqt

ttygqcqt1#

distinct只接受一个布尔值作为参数来指定记录是否应该是唯一的。所以distinct(:viewable_id)等效于distinct(true),而不是做你想做的事情。你应该使用distinct,而不是使用group,它根据组属性返回一个具有不同记录的数组。要返回最近的一个,除了按created_at排序(使用order)之外,还需要在group中添加字段:

@views = StoreView
         .order(viewable_id: :desc, viewable_type: :desc, created_at: :desc)
         .group(:viewable_id, :viewable_type)

字符串
如果您需要将返回的记录按created_at排序,则需要添加以下内容。

anhgbhbe

anhgbhbe2#

如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。有几种方法可以work around this issue
在这个例子中,使用聚合函数应该可以工作:

@views = StoreView
           .select('DISTINCT viewable_type, viewable_id, MAX(created_at)')
           .group(:viewable_type, :viewable_id)
           .order('MAX(created_at) DESC')
           .limit(10)

字符串

lp0sw83n

lp0sw83n3#

ActiveRecord distinct:
https://apidock.com/rails/ActiveRecord/QueryMethods/distinct
指定记录是否应该是唯一的。例如:

User.select(:name)
# => Might return two records with the same name

User.select(:name).distinct
# => Returns 1 record per distinct name

字符串
不如这样吧:

@views = StoreView
    .select(:viewable_id, :viewable_type)
    .distinct
    .order("created_at DESC")
    .limit(10)


你也可以尝试

@views = StoreView
    .select('DISTINCT `viewable_id`, `viewable_type`')
    .order("created_at DESC")
    .limit(10)

相关问题