在一个ActiveRecord查询中应用两个范围

时间:2013-03-03 07:19:25

标签: ruby-on-rails ruby-on-rails-3.2 rails-activerecord

我的计划模型有:

has_many :registry_patient_counts
scope :salary_and_bonus, 
  :joins => :registry_patient_counts,
  :order => "patient_count_percentage DESC"

当我使用我的控制器开始简单的步骤时,这很有效:

programs = 
  Program.includes([:registry_patient_counts])
    .salary_and_bonus.where('organization_id = 1')
    .limit(2)

但是我的终极控制器看起来应该是这样的(如果没有范围,它看起来如何)

@programs = Program.includes(
  [:registry_patient_counts, measures: :measures_off_targets])
  .where('organization_id = 1')
  .limit(2)

所以请注意它中有measures: :measures_off_targets个额外内容。 所以在measure和measures_off_targets之间我也想要定义一个与前一个类似的范围....但是我不明白如何在控制器中键入这两个范围?


编辑:所以这是我们到目前为止所遵循的答案:

在Program.rb中:

scope :rpc,   includes(:registry_patient_counts).order => "patient_count_percentage DESC"

scope :msr, includes(measures: :measures_off_targets)

控制器查询如下所示:

@programs2 = Program.rpc.msr.where('organization_id: 1').limit(2)

RubyMine在IDE中显示的错误是“找不到msr” 如果我忽略它并转到浏览器,仍然在Rail控制台中我收到“错误500,错误请求”并且没有任何回复。

1 个答案:

答案 0 :(得分:0)

您可以链接范围和包含。

scope :rpc, includes(:registry_patient_counts)
scope :msr, includes(measures: :measures_off_targets)

@programs = Program.rpc.msr.where(organization_id: 1).limit(2)

# Equivalent to
@programs = Program.includes(
  [:registry_patient_counts, measures: :measures_off_targets])
  .where(organization_id: 1)
  .limit(2)