Rails:如何获得直接相关的记录,但是在关系的背景下:通过

时间:2018-01-19 07:56:36

标签: ruby-on-rails ruby

我有一种奇怪的情况,我有一个DayReport有很多报告,属于一个帐户。我使用has_many来为帐户设置我的DayReport模块:

class DayReport < ActiveRecord::Base
  has_many :reports
  has_many :accounts, -> { order(:last_name) }, through: :reports
end

我现在要做的是获取所有帐户并显示该帐户的所有报告,但前提是它们与DayReport相关。我不能使用account.reports,因为它还包含其他报告。

我采用的一种方法是创建一个使用where子句获取相应报告的实例方法:

  def reports_for_account account
    reports.where(account: account)
  end

问题是这会触发每个帐户的查询,我认为这是不必要的。我只是在弄清楚正确的方法。

2 个答案:

答案 0 :(得分:1)

我希望我理解正确。

您可以使用eager loadet association使用.includes来减少quires的数量,因为includes会加载(1.查询)父项的所有记录和(2. query)所引用的所有记录在include方法中(where)。

.where中,您可以查看day_report ID是否存在或是否为某个ID(我不太确定您在此处提出的问题)

例如(带id):

Account.includes(:reports).where(reports: {day_report_id: specified_id})

或者如果他们有关系:

Account.includes(:reports).where.not(reports: {day_report_id: nil})

这会将查询数量减少到两个。

希望它有所帮助!

答案 1 :(得分:0)

也许joins会帮助你:

Account.includes(:reports).joins(:day_reports) 它会获取所有在DayReport中有记录并预先加载reports的帐户。