迭代named_scope内的has_many集合
这是我的模型:
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
这是我想要做的:我想在消息中创建一个名为 unread
的named_scope,如果消息的任何评论或消息本身未读,它基本上返回 true未读。我有办法做到这一点吗?
Here are my models:
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
Here is what I am looking to do: I'd like to create a named_scope in Message, called unread
that basically returns true if any of the message's comments are unread or the message itself is unread. Is there a way I can do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个怎么样:
How about this:
为什么命名范围?你可以这样做
,或者,如果它需要是一个类方法,
但是你真的想要使用命名范围吗,你会想要这样的东西:
Why the named scope? You could just do
or, if it needs to be a class method
Is you really do want to use named scopes though, you'll want something like this: