2012-11-11 25 views
0

我有一個Notification模型,其中有很多列是「未讀」。在Rails中過濾ActiverRecord集合

我需要使用簡單的方法在@notification集合中查找其中「未讀」值爲false的記錄。這樣的:

@notifications= Notification.all 
@notifications.unread --> returns a subset of @notifications which are unread 
@notifications.unread.count --> returns number of unread notifications 

如何使這個「未讀」的方法?

回答

2

爲此,您可以一次將類方法範圍

class Notification 
    def self.unread 
    where(:unread => true) # depends on your data type 
    end 
end 

class Notification 
scope :unread, where(:unread => true) # depends on your data type 
end 

只是調用該方法對通知

Notification.unread # => returns unread notifications 
Notification.unread.count # => returns number of unread notifications 
3

一種方法是通過將以下內容添加到Notification類中來創建scope

scope :unread, where(unread: true) 

瞭解範圍here

+0

這正是我想要的。謝謝。 –