代码之家  ›  专栏  ›  技术社区  ›  Jeremy Thomas

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

  •  0
  • Jeremy Thomas  · 技术社区  · 7 年前

    Client CheckIn :

    class Client < ActiveRecord::Base
        has_many :check_ins
    end
    
    class CheckIn < ActiveRecord::Base
        belongs_to :client
    end
    

    通常当我把所有的 :check_ins 为了 :client 我打电话给:

    Client.find(1).check_ins
    

    我注意到 :签入 返回最近的10条记录,以及最早的记录 #<ActiveRecord::AssociationRelation

    我怎么才能做到呢?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Ilya Konyukhov    7 年前

    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

        2
  •  -1
  •   R. Sierra    7 年前

    我认为 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