【发布时间】: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