【问题标题】:Rails Union Table and sort by common keyRails 联合表并按公共键排序
【发布时间】:2017-06-19 13:59:08
【问题描述】:

我在 Rails 应用程序 Match 和 Round 中有两个模型如下

Match(id, team1, team2, series_id, event_time, event_lock_time, match_type, created_at, updated_at, match_no, match_stage)

Round(id, series_id, name, description, event_time, event_lock_time, team_ids, matches_count, created_at, updated_at)

我想添加两个表并根据 created_at 对记录进行排序

events = (Match + Round).order('created_at desc').paginate(:page => params[:page], :per_page => params[:per_page])

并且还应用分页。我正在使用 will 分页 gem。

谁能帮助我如何在活动记录中做到这一点。

【问题讨论】:

  • 你能分享你的模型吗?它们之间是否有任何关联?
  • 不,我在 Match 和 Round 模型之间没有任何关联

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

据我所知,模型没有 + 运算符。所以你不能这样做:

(Match + Round)

但你可以添加 Active Record 关系:

matches = Match.all
rounds = Round.all
(matches + rounds).sort_by(&:created_at)

您必须使用 sort_by 或类似方式,因为 (matches + rounds) 是数组而不是 Active Record 关系(因此未定义 order)。

更新: 我猜您正在使用 will_paginate 对结果进行分页。它仍然适用于数组,但你必须告诉它,你可以通过两种方式告诉它:

  1. 将此添加到控制器顶部:require 'will_paginate/array'
  2. 创建一个初始化器 config/initializers/will_paginate_with_array.rb 并在此文件中要求它。

那么,你可以这样做:

(matches + rounds).sort_by(&:created_at).paginate(:page => params[:page], , :per_page => params[:per_page])

【讨论】:

  • 嘿感谢您的回复,但我想对结果进行分页,因为我必须通过 api 请求提供数据。
猜你喜欢
  • 1970-01-01
  • 2012-12-08
  • 2012-12-05
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多