Ruby on rails ActiveRecord条件作用域

Ruby on rails ActiveRecord条件作用域,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我试图在我的项目中创建某种条件作用域,但不知道如何处理它 我有一个医疗机构,是医生 class Practice < ActiveRecord::Base has_many :doctors, -> { where removed_at: nil } end class Doctor < ActiveRecord::Base scope :with_all_doctors, -> {includes(:practi

我试图在我的项目中创建某种条件作用域,但不知道如何处理它

我有一个医疗机构,是医生

    class Practice < ActiveRecord::Base
        has_many :doctors, -> { where removed_at: nil }
    end

    class Doctor < ActiveRecord::Base
        scope :with_all_doctors, -> {includes(:practice).where.not removed_at: nil}       
        belongs_to :practice
    end

我将非常感谢您的解决方案。

我认为您正在使您的情况复杂化。为什么不像这样

class Practice < ActiveRecord::Base
  has_many :doctors
end

class Doctor < ActiveRecord::Base
  belongs_to :practice

  scope :active, -> { where :removed_at => nil }
  scope :inactive, -> { where("removed_at is not null") }
end
课堂实践{where:removed_at=>nil}
作用域:非活动,->{where(“removed_at不为null”)}
结束

这样,你可以做
docs=Practice.find(params[:id]).doctors
来获取所有的医生,然后根据你的需要对活跃的和不活跃的医生进行
docs.active
或者
docs.inactive

好吧,在现实生活中,我有更深层的对象层次结构,我不想手动合成它。我需要获得正确的结构,并将其作为json发送到客户端的应用程序。如果您向我们提供层次结构的“图片”,我们也可以为其提出解决方案。我认为提供的结构足够(由于NDA,无法公开更多)用于演示目的。我只需要一种获得所需结构的方法,而不必直接对其模型对象调用范围。
class Practice < ActiveRecord::Base
  has_many :doctors
end

class Doctor < ActiveRecord::Base
  belongs_to :practice

  scope :active, -> { where :removed_at => nil }
  scope :inactive, -> { where("removed_at is not null") }
end