0

我有以下型号:

class Notification < ActiveRecord::Base

belongs_to :notificatable, polymorphic: true

end

class BounceEmailNotification < ActiveRecord::Bas

has_one :notification, :as => :notificatable, :dependent => :destroy

end

class UserNotifierEmailNotification < ActiveRecord::Base

has_one :notification, :as => :notificatable, :dependent => :destroy

end

如您所见,通知可以是“退回电子邮件通知”或“用户通知电子邮件通知”类型。该BounceEmailNotification模型具有事件字符串属性。如果我想检索具有特定事件值的所有用户通知电子邮件通知和所有退回电子邮件通知,该created_at怎么办?

像这样的东西(使用squeel):

(Notification.joins{ notificatable(BounceEmailNotification) }.where('bounce_email_notifications.event' => 'error') + Notification.joins { notificatable(UserNotifierEmailNotification) }).sort_by { |n| n.created_at }

会工作,但我不想使用 Ruby 来订购通知。我能做些什么?谢谢

4

1 回答 1

0

试试这个。

Notification.joins('left outer join bounce_email_notifications on notifications.notificatable_id = bounce_email_notifications.id and notificatable_type = "BounceEmailNotification"').
where("bounce_email_notifications.event = ? or notificatable_type = ?",'error',UserNotifierEmailNotification.to_s).
order('notifications.created_at')

这是使用活动记录 3.2,但我想它应该在 rails 3 中工作。

我没有使用 squeel 不能对如何将它与 squeel 一起使用发表太多评论,但这可以给你一个简短的想法。

在 squeel 中,我想出了使用 squeel文档创建的类似(未测试)的东西

Notification.notificatable{notable(BounceEmailNotification).outer}. where{
         { ('bounce_email_notifications.event'=>'error') | (:notificatable_type=>UserNotifierEmailNotification.to_s) }

概念步骤

  1. 在bounce_email_notifications 上左加入以获得所有bounce_email_notifications 和非bounce_email_notifications 通知结果

  2. 检查所有 UserNotifierEmailNotification 记录的bounce_email_notifications.event = event
    或notificatable_type = 'UserNotifierEmailNotification'

  3. 按通知排序记录。创建于

希望这可以帮助。

于 2013-04-19T06:40:40.713 回答