[英]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.