Rails:返回有限数量的记录以及第一个

时间:2018-09-20 16:39:20

标签: ruby-on-rails

我有2个Rails模型,imageOutputlibrary(xray) library(shiny) ui <- fluidPage( imageOutput("Distribute1"), imageOutput("Distribute2") ) server <- function(input, output, session) { png("x%03d.png") xray::distributions(longley, charts = T) dev.off() output$Distribute1 <- renderImage({ list(src = "x001.png") }, deleteFile = FALSE) output$Distribute2 <- renderImage({ list(src = "x002.png") }, deleteFile = FALSE) } shinyApp(ui, server)

Client

通常,当我为CheckIn提取所有class Client < ActiveRecord::Base has_many :check_ins end class CheckIn < ActiveRecord::Base belongs_to :client end 时会打电话给

:check_ins

我注意到随着:client数量的增加,我在浪费内存,因此我想返回最近的10条记录以及最旧的一条记录。我还希望返回的项是Client.find(1).check_ins 而不是数组。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

UNION可以在单个SQL查询中合并最新记录和最新记录。所以你可以这样写:

query = "(SELECT * FROM #{CheckIn.table_name} WHERE client = :client_id ORDER BY created_at DESC LIMIT 10) UNION (SELECT * FROM #{CheckIn.table_name} WHERE client = :client_id ORDER BY created_at ASC LIMIT 1)"
CheckIn.find_by_sql [query, { client_id: client_id }]

但是结果将是Array,而不是ActiveRecord::AssociationRelation

答案 1 :(得分:-1)

我认为scoping是您要寻找的

  class CheckIn < ActiveRecord::Base
    belongs_to :client
    scope :recent, -> { order(created_at: :desc).limit(10) }
    scope :oldest, -> { order(created_at: :asc).limit(10) }
  end

  > Client.find(1).check_ins.recent
  => #<ActiveRecord::AssociationRelation [ ...]>
  > Client.find(1).check_ins.oldest