Ruby on rails 使用第二个字段订购日期相同的记录

Ruby on rails 使用第二个字段订购日期相同的记录,ruby-on-rails,activerecord,ruby-on-rails-4,scope,arel,Ruby On Rails,Activerecord,Ruby On Rails 4,Scope,Arel,我有一份有很多画廊的申请。每个库都有一个开始日期时间字段 出于传统原因,所有开始日期的时间均为午夜 Thu, 10 Jul 2014 00:00:00 UTC +00:00 我需要按日期排列图库,这样用户可以使用“旧”和“新”链接在图库之间来回移动。画廊是根据开始日期订购的: scope :start_date_ascending, -> { order(start_date: :asc) } scope :start_date_descending, -> { order(sta

我有一份有很多画廊的申请。每个库都有一个开始日期时间字段

出于传统原因,所有开始日期的时间均为午夜

Thu, 10 Jul 2014 00:00:00 UTC +00:00
我需要按日期排列图库,这样用户可以使用“旧”和“新”链接在图库之间来回移动。画廊是根据开始日期订购的:

scope :start_date_ascending, -> { order(start_date: :asc) }
scope :start_date_descending, -> { order(start_date: :desc) }
我的问题是,当有多个相同日期的库时,没有清晰的旧库或新库。在这种情况下,我无法预测具有相同日期的库返回的顺序,因此在具有相同日期的多个库之间移动变得随机且容易出错

我已设置查找较新和较旧画廊的范围:

scope :newer_than, -> (gallery){ where.not(id:gallery).where('start_date >= :gallery_start_date', gallery_start_date:gallery.start_date) }
scope :older_than, -> (gallery){ where.not(id:gallery).where('start_date < :gallery_start_date', gallery_start_date:gallery.start_date) }
所以在我看来,我需要第二种方式来订购同一日期的画廊。不管是什么顺序,它可能只是他们的ID


我如何处理这种情况,使具有相同日期的库以可预测的固定顺序出现在查询中,以便
next\u newer
next\u older
在它们之间移动?

也许您可以使用第二个条件进行排序,例如
name
,如果可用,甚至
id

scope :start_date_ascending, -> { order(start_date: :asc, name: :asc) }
scope :start_date_descending, -> { order(start_date: :desc, name: :asc) }
注意:在
开始日期\u降序
范围中,保留name
asc
是很好的,因此,尽管有降序日期顺序,我们仍保持字母顺序

对于下一个和上一个库,如果您可以存储一个数组,那么您可以获得有序的ID并遍历它们

ids = Gallery.start_date_ascending.pluck :id

根据@BengaminSinclaire的建议:

  def self.next_newer(gallery)
    ascending_ids = Gallery.start_date_ascending.pluck :id
    current_index = ascending_ids.index(gallery.id)
    Gallery.find(ascending_ids[current_index+1]) if current_index < ascending_ids.length - 1
  end

  def self.next_older(gallery)
    ascending_ids = Gallery.start_date_ascending.pluck :id
    current_index = ascending_ids.index(gallery.id)
    Gallery.find(ascending_ids[current_index-1]) if current_index > 0
  end
def self.next\u更新(图库)
升序\u id=Gallery.start\u date\u升序.pluck:id
当前索引=升序索引(gallery.id)
如果当前索引<升序ID.length-1,则查找(升序ID[当前索引+1])
结束
def自我。下一个旧版本(图库)
升序\u id=Gallery.start\u date\u升序.pluck:id
当前索引=升序索引(gallery.id)
如果当前索引>0,则查找(升序索引ID[当前索引-1])
结束

谢谢。虽然这确实可以处理订单,但不能解决查询问题。我仍然需要一种方法来确保查询返回给定库之前或之后的库。然后,我如何查询开始日期早于给定画廊的画廊,或者(日期相同且名称早于给定画廊)您可以存储
id
s的数组
ids=Gallery.start\u date\u升序.pluck:id
。然后遍历该数组
  def self.next_newer(gallery)
    ascending_ids = Gallery.start_date_ascending.pluck :id
    current_index = ascending_ids.index(gallery.id)
    Gallery.find(ascending_ids[current_index+1]) if current_index < ascending_ids.length - 1
  end

  def self.next_older(gallery)
    ascending_ids = Gallery.start_date_ascending.pluck :id
    current_index = ascending_ids.index(gallery.id)
    Gallery.find(ascending_ids[current_index-1]) if current_index > 0
  end