2013-04-18 52 views
0

我有以下型號:的Rails 3:多態查詢條件

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來訂購通知。我能做什麼?謝謝

回答

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,但我想它應該在軌運行3

我還沒有就如何處理squeel使用它,但這個可以給你一個簡單的想法使用squeel着很多評論。

在squeel我想出了這樣的事情(未測試)創建使用squeel docs

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. 檢查bounce_email_notification s.event =事件
    或 notificatable_type = 'UserNotifierEmailNotification' 用於所有UserNotifierEmailNotification記錄

  3. 排序記錄由notifications.created在

希望這有助於。