【问题标题】:Rails ActiveRecord 4.2 custom sort orderRails ActiveRecord 4.2 自定义排序顺序
【发布时间】:2016-11-21 08:12:17
【问题描述】:

我正在尝试将自定义范围或类方法应用于以下 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 模型有一个 event_type 属性,它具有 3 个不同字符串值中的 1 个(即上午、下午、晚上)。

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

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

# 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 响应发送。目前,这种重新排序是在客户端完成的,但是我试图在返回给客户端之前以所需的顺序呈现初始结果。

【问题讨论】:

    标签: ruby-on-rails-4 activerecord named-scope


    【解决方案1】:

    您可以使用 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" }  
    

    【讨论】:

    • 我会小心的。以任何其他顺序显示event_booking.events 可能会变得困难(有点像default_scope。也许更安全地将这个范围放在事件模型上,然后像event_bookings.events.event_type_order 或类似的东西一样调用它。
    • 我采纳了您的建议并在事件模型中创建了一个命名范围,而不是通过关系传递范围。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多