简体   繁体   中英

Rails query which returns all records having exactly ZERO associated record with condition

Here's my associations:

class Insights::Visitor < ActiveRecord::Base
  has_many :conversations,
    class_name: "Chat::Conversation",
    foreign_key: :chat_visitor_id
end

class Chat::Conversations < ActiveRecord::Base
  belongs_to :chat_visitor,
      class_name: "Insights::Visitor",
      foreign_key: "chat_visitor_id"

   enum status: {
      open: "open",
      closed: "closed",
      pending:  "pending",
      spam:  "spam",
      trash: "trash"
    }
end

My use case is pretty straightforward. I want to get visitor count without any open conversations or scope in Visitor model which returns all visitors having exactly ZERO associated conversations whose status is "open".

Presently I'm using Ruby to do it for the most part like so:

def visitor_count_without_open_conversations
    online_visitors = organization.visitors.includes(:conversations).online
    count = 0
    online_visitors.each do |visitor|
      if visitor.conversations.search_with_status("open").size == 0
        count +=1
      end
     end 
    return count
  end
end

which sucks because this isn't a good use-case for Ruby. But I'm struggling to figure out how to do this using SQL.

Can someone let me know a good, clean SQL solution to this?!

Here's my associations:

class Insights::Visitor < ActiveRecord::Base
  has_many :conversations,
    class_name: "Chat::Conversation",
    foreign_key: :chat_visitor_id
end

class Chat::Conversations < ActiveRecord::Base
  belongs_to :chat_visitor,
      class_name: "Insights::Visitor",
      foreign_key: "chat_visitor_id"

   enum status: {
      open: "open",
      closed: "closed",
      pending:  "pending",
      spam:  "spam",
      trash: "trash"
    }
end

My use case is pretty straightforward. I want to get visitor count without any open conversations or scope in Visitor model which returns all visitors having exactly ZERO associated conversations whose status is "open".

Presently I'm using Ruby to do it for the most part like so:

def visitor_count_without_open_conversations
    online_visitors = organization.visitors.includes(:conversations).online
    count = 0
    online_visitors.each do |visitor|
      if visitor.conversations.search_with_status("open").size == 0
        count +=1
      end
     end 
    return count
  end
end

which sucks because this isn't a good use-case for Ruby. But I'm struggling to figure out how to do this using SQL.

Can someone let me know a good, clean SQL solution to this?!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM