[英]Iterating over a has_many collection within a named_scope
這是我的模型:
class Message < ActiveRecord::Base
has_many :comments
attr_accessible :read #bool
def unread_comments?
comments.each { |comment| return true unless comment.read?}
false
end
end
class Comment < ActiveRecord::Base
belongs_to :message
attr_accessible :read #bool
end
這是我要執行的操作:我想在Message中創建一個named_scope,稱為unread
,如果任何一條消息的注釋未讀或消息本身未unread
,則基本上返回true。 有辦法嗎?
class Message < AR::Base
...
def unread?
!self.read && !self.comments.all?(&:read)
end
end
這個怎么樣:
named_scope :unread, :conditions => ['messages.read = ? OR comments.read = ?',
false, false],
:include => :comments
為什么命名范圍? 你可以做
def has_unread
!self.read || unread_comments?
end
或者,如果需要它是一個類方法
def self.has_unread(message)
msg = Message.find(message.id)
msg.read == false && msg.unread_comments?
end
您是否確實確實想使用命名范圍,但您會想要這樣的東西:
scope :get_unreads, lambda {|message|
{ :joins => :comments,
:conditions => {:comments => {:message_id => message.id}, :message => ['read',0]},
:select => "DISTINCT `clients`.*" # kill duplicates
}
}
def self.has_unread?(message)
self.get_unreads(message).exists? && self.find(message.id).read
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.