【问题标题】:ActiveRecord conditional scopesActiveRecord 条件范围
【发布时间】:2014-11-28 15:53:52
【问题描述】:

我正在尝试在我的项目中创建某种条件范围,但不知道如何处理。

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

    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

现在我希望能够找到一些实践和所有的医生,以及只有在职医生的实践(removed_at == nil)

我正在尝试实现以下目标:

    doctor = Doctor.find(id: params[:id]) #here we are fetching object hierarchy 
#with only active doctors of practice 
#(doctor.practice.doctors will give only active users)

    doctor = Doctor.with_all_doctors.find(id: params[:id]) #here we need to fetch object hierarchy 
#with all doctors of practice 
#(doctor.practice.doctors will give both active and removed doctors)

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

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    我认为你让你的情况复杂化了。为什么不这样呢?

    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
    

    这样,您可以通过docs = Practice.find(params[:id]).doctors 获取所有医生,然后根据您的需要docs.activedocs.inactive 获取活跃和非活跃医生。

    【讨论】:

    • 嗯,在现实生活中我有更深的对象层次结构,我不想手动组合它。我需要获得正确的结构并将其作为 json 发送到客户端的应用程序。
    • 如果您向我们提供层次结构的“图片”,我们也可以提出解决方案。
    • 我认为提供的结构就足够了(由于 NDA 不能公开更多)用于演示目的。我只需要一种方法来获得所需的结构,而不必直接在其模型对象上调用范围。
    猜你喜欢
    • 2014-10-11
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多