rails选择不同的嵌套关联并获取这些关联

时间:2015-05-16 05:03:21

标签: sql ruby-on-rails postgresql activerecord

我有模型UserCompanyProductView

class Company < ActiveRecord::Base
  has_many :users
end

class Product < ActiveRecord::Base
  has_many :views_by_user, -> { where viewable_type: User },
  as: :viewable, class_name: "View"
end

class User < ActiveRecord::Base
  has_many :viewed, as: :viewer, class_name: "View"
  belongs_to :company
end

class View < ActiveRecord::Base
  belongs_to :viewable, polymorphic: true
  belongs_to :viewer, polymorphic: true
end

我对上述内容的处理是,当用户查看产品时,我将数据保存在views

现在我想要查看我的产品(通过companies)的不同user列表和我的序列化程序的总计数。我所做的是,

distinct_users = @product.views_by_user
    .includes(viewer: [:company])
    .joins("left outer join users on views.viewer_id = users.id")
    .select("distinct users.company_id, views.*")

但有了这个,我必须做类似

的事情
distinct_users.will_paginate(...).map(&:viewer).map(&:company)

有更好的方法吗?如果我使用distinct_users.count它也会引发错误

PG::UndefinedFunction: ERROR:  function count(integer, views) does not exist
LINE 1: SELECT COUNT(distinct users.company_id,...

1 个答案:

答案 0 :(得分:1)

如果这是您真正想要的记录类型,请从merge开始。您可以使用Company.joins(:users => :viewed).merge(View.where(viewable: @product))将关系条件与另一条关系的条件进行组合。试试这个:

criteria = Criteria.where("dob").lte(new DateTime().toDate());

HTH