将两个ActiveRecord查询与分页相结合

时间:2015-08-14 16:46:02

标签: ruby-on-rails activerecord pagination

我有两个有效的记录查询:

feedbacks = Activity.where(subject_type: Feedback.name).select{ |f| f.subject.application == @application }
activities = Activity.where(subject: @application)
                    .order(created_at: :desc).page(params[:page])
                    .per(10) + feedbacks

我觉得必须有更好的方法来组合这两个查询的结果。此外,由于feedbacks可能会返回n条记录,因此分页无法正常工作。

如果我在两个查询中添加了分页,那么我可以获得比实际想要显示的项目多一倍的项目。

编辑:这是一个似乎有效的尝试 - 不是很好:

activities = Activity.where('subject_id = ? OR subject_type = ?', @application.id, Feedback.name)
  .order(created_at: :desc)
  .page(params[:page])
  .per(20).select { |record|
    if record.subject_type == Feedback.name
      record.subject.application == @application
    else
      true
    end
  }

1 个答案:

答案 0 :(得分:0)

将此添加到您的活动模型:

belongs_to :feedback, -> { where(activities: {subject_type: 'Feedback'}) }, foreign_key: 'subject_id'

然后在你的控制器中:

feedbacks = Activity.includes(:feedback).where(feedbacks:{application:@application})
other_activities = Activity.where(subject: @application)
matching_ids = (feedbacks.map(&:id)+other_activities.map(&:id))
activities = Activity.where(id:matching_ids).order(created_at: :desc).page(params[:page])

这个解决方案实际上不是可扩展的,因为基于多态关联的两个条件,你应该做一个非常复杂的查询