簡體   English   中英

has_many 通過 => 找到不匹配的記錄

[英]has_many through => find not matching records

我希望能夠找到無人居住的蕁麻疹,但找不到任何解決方案。 你能幫我嗎? 目標是能夠做到 Hive.unpopulated 主要問題是 most_recent,但我可以使用原始 SQL,但我找不到正確的查詢。

這是我的課程:

class Hive < ApplicationRecord
  has_many :moves, dependent: :destroy
  has_many :yards, through: :moves
  has_many :populations, -> { where(:most_recent => true) }
  has_many :colonies, through: :populations 
  
  validates :name, uniqueness: true
  
  def hive_with_colony 
    "#{name} (colony #{if self.colonies.count > 0 then self.colonies.last.id end})"
  end
  
  def self.populated
    Hive.joins(:populations)
  end
  def self.unpopulated
    
  end
  
end
class Population < ApplicationRecord
  belongs_to :hive
  belongs_to :colony
  
  after_create :mark_most_recent
  before_create :mark_end
class Colony < ApplicationRecord
  has_many :populations, -> { where(:most_recent => true) }
  has_many :hives, through: :populations
  has_many :visits
  has_many :varroas
  
  has_many :most_recents_populations, -> { where(:most_recent => true) }, :class_name => 'Population'
  scope :last_population_completed, -> { joins(:populations).where('populations.most_recent=?', true)}

我認為您可以對不在填充列表中的 select Hives 進行簡單查詢,因此:

def self.unpopulated
  where.not(id: populated.select(:id))
end

另一個選項是LEFT OUTER JOIN並選擇右側沒有設置人口 ID 的行。

def self.unpopulated
  left_outer_joins(:populations).where(populations: { id: nil })
end

如果 Thanh 的版本(比較潛在的巨大 id 列表)或這個版本(它使連接看起來更復雜,但不需要與 id 列表比較)性能更高,這取決於您的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM