【问题标题】:Iterating over a has_many collection within a named_scope迭代 named_scope 内的 has_many 集合
【发布时间】:2011-03-16 19:20:57
【问题描述】:

这是我的模型:

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,如果任何消息的 cmets 未读或消息本身未读,它基本上返回 true。有什么办法可以做到吗?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord named-scope


    【解决方案1】:
    class Message < AR::Base
      ...
      def unread?
        !self.read && !self.comments.all?(&:read)
      end
    end
    

    【讨论】:

      【解决方案2】:

      这个怎么样:

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

      【讨论】:

        【解决方案3】:

        为什么是命名范围?你可以这样做

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-10
          • 2018-04-08
          • 2011-04-25
          • 1970-01-01
          • 1970-01-01
          • 2015-08-17
          相关资源
          最近更新 更多