2012-11-11 4 views
0

나는 Notification 모델을 가지고 있는데 그 중 하나가 많은 열이 "읽지 않음"입니다.레일에서 ActiverRecord 컬렉션 필터링하기

간단한 방법을 사용하여 "읽지 않은"값이 false 인 레코드를 @notification 컬렉션에서 찾아야합니다. 예 :

@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

이것은 정확히 내가 원했던 것입니다. 감사. –

관련 문제