【问题标题】:has_many through => find not matching recordshas_many 通过 => 找到不匹配的记录
【发布时间】:2021-04-23 00:48:50
【问题描述】:

我希望能够找到无人居住的荨麻疹,但找不到任何解决方案。 你能帮我吗 ? 目标是能够做 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)}

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6.1


    【解决方案1】:

    另一个选项是 LEFT OUTER JOIN 并选择右侧没有设置人口 ID 的行。

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

    这取决于您的数据,如果 Thanh 的版本(比较可能巨大的 id 列表)或这个版本(它使连接看起来更复杂,但不需要与 id 列表进行比较)性能更高。

    【讨论】:

      【解决方案2】:

      我认为你可以做一个简单的查询来选择不在填充列表中的 Hives,所以:

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

      【讨论】:

      • 哇,谢谢。我知道 Rails 有一个简单的方法!
      猜你喜欢
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多