使用OR运算符进行ActiveRecord查询

时间:2015-01-14 12:50:21

标签: ruby-on-rails activerecord arel

我有ActiveRecord模型类,其范围如下所示。

scope :acknowledgeable, -> { with_message.where(messages: { acknowledgeable: true }) }
scope :acknowledged, -> { acknowledgeable.where.not(acknowledged_at: nil) }
scope :not_acknowledged, -> { acknowledgeable.where(acknowledged_at: nil) }
scope :not_read, -> do
  message_statuses = MessageStatus.arel_table
  messages = Message.arel_table
  GuestMessageStatus.joins(:message).where(
    message_statuses[:read_at].eq(nil)
    .or(
      messages[:acknowledgeable].eq(true)
      .and(message_statuses[:read_at].eq(nil))
      .and(message_statuses[:acknowledged_at].eq(nil)))
 )
end

范围not_read是我关注的对象。基本上它可以正常工作。它可以用更优雅,更简单的方式编写吗?我不想用原始SQL编写它。

时,状态消息被视为已读
if status.message.acknowledgeable?
  status.read_at.nil? && status.acknowledged_at.nil?
else
  status.read_at.nil?
end

0 个答案:

没有答案