通过多个关联模型进行单个ActiveRecord查询

时间:2017-04-20 14:00:07

标签: ruby-on-rails ruby activerecord

我有以下模特和协会:

organization.counter_records(dimension_day: start_date...end_date)

我想得到类似的东西

[dimension_day: start_date...end_date]

organization - 这是条件)。

如何通过所有这些模型获得datess <- seq(as.Date('2005-01-01'), as.Date('2009-12-31'), 'days') sample<- data.frame(matrix(ncol = 3, nrow = length(datess))) colnames(sample) <- c('Date', 'y', 'Z') sample$Date <- datess 的计数器记录?

1 个答案:

答案 0 :(得分:5)

查看Activerecord Querying guide

具体而言,您对joins感兴趣:

Organization.joins(buildings: { counters: :counter_records })
            .where(counter_records: { dimension_day: start_date...end_date })
            .group('organizations.id')

您可以创建一个方法:

class Organization
  def filter_counter_records(start_date, end_date)
    self.class
        .where(id: id)
        .joins(buildings: { counters: :counter_records })
        .where(counter_records: { dimension_day: start_date...end_date })
        .group('organizations.id')
  end
end

现在可以进行以下操作:

organization = Organization.first
organization.filter_counter_records(start_date, end_date)

但更惯用/传统的选择是使用关联:

class Organization
  has_many :buildings
  has_many :counters,        through: :buildings
  has_many :counter_records, through: :counters
end

现在你可以选择

organization = Organization.first
organization.counter_records.where(dimension_day: start_date..end_date)

此处的最后一步是设置CounterRecord中的scope

class CounterRecord
  scope :by_date_range, ->(start_date, end_date) { where(dimension_day: start_date..end_date) }
end

现在

organization = Organization.first
organization.counter_records.by_date_range(start_date, end_date)