Rails ActiveRecord 4.2 自定义排序顺序

Rails ActiveRecord 4.2 custom sort order

我正在尝试将自定义范围或 class 方法应用于以下 ActiveRecord 模型,但是我不确定 Rails 最佳实践的最佳方法或实施。

请注意,这只是一个用于解释目的的简化示例项目。

# event_booking.rb
class EventBooking < ActiveRecord::Base
  has_many :events, -> { order('event_type ASC') }, dependent: :destroy
end

# event.rb
class Event < ActiveRecord::Base
  belongs_to :event_booking
end

# event_bookings_controller.rb
class EventBookingController < ApplicationController
  def show
    @event_booking = EventBooking.find(params[:id])
  end
end

事件模型有一个 event_type 属性,具有 3 个不同字符串值中的 1 个(即早上、下午、晚上)。

当前的问题是字符串不是按字母顺序排列的,因此我无法使用标准的 ASC 或 DESC 来对事件集合进行排序。

到目前为止,我考虑过对事件模型进行 3 个单独的查询,然后在 class 方法中将结果组合到一个数组中。我也曾尝试做类似以下的事情,但没有成功。

# event_booking.rb
class EventBooking < ActiveRecord::Base
  has_many :events, -> { order(%w(morning afternoon evenint).map { |cond| where(event_type: "#{cond}") }.join(', ')) }, dependent: :destroy
end

我的目标是使用类似于 @event_booking.events@event_booking.events_by_type 的方式从控制器访问单个有序事件集合,顺序如下 event_type:

- morning
- afternoon
- evening

调用的结果作为对 API 调用的 JSON 响应发送。目前,这种重新排序是在客户端完成的,但是我试图在将初始结果返回给客户端之前以所需的顺序呈现初始结果。

您可以使用 sql case 语句来控制顺序。

has_many :events, ->{ "ORDER BY CASE WHEN event_type = 'morning' THEN '1' WHEN event_type = 'afternoon' THEN '2' WHEN event_type = 'evening' THEN '3' END" }