迭代named_scope中的has_many集合

时间:2011-03-16 19:20:57

标签: ruby-on-rails ruby activerecord 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中创建一个名为unread的named_scope,如果任何消息的注释未读或消息本身未读,则基本上返回true。有没有办法可以做到这一点?

3 个答案:

答案 0 :(得分:3)

class Message < AR::Base
  ...
  def unread?
    !self.read && !self.comments.all?(&:read)
  end
end

答案 1 :(得分:2)

这个怎么样:

named_scope :unread, :conditions => ['messages.read = ? OR comments.read = ?', 
                                      false, false],
                     :include => :comments

答案 2 :(得分:1)

为什么命名范围?你可以做到

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