预加载动态过滤has_many与ActiveRecord的关联

时间:2018-01-07 20:49:18

标签: ruby-on-rails activerecord associations ruby-on-rails-5.1

我正在尝试包含/预加载具有动态运行时条件的has_many关联。我得到了正确的结果,但我的变量是硬编码的,我不知道如何从包含中传递它。

我的查询:

@volunteers = Volunteer.includes({ signups: [{position: [{ eventday: :event }] }] }, :event_survey_results).where(events: { id:  @event.id })

志愿者模式:

class Volunteer < ApplicationRecord
  # Hard coded solution works
  has_many :event_survey_results, -> { where event_id: 60 }, class_name: 'Questionnaires::SurveyResult'
end
  # Dynamic solution. How to pass event_id to this from :includes ?
  has_many :event_survey_results, ->(event_id) { where event_id: event_id }, class_name: 'Questionnaires::SurveyResult'
end

我需要在:includes语句中将event_id传递给event_survey_results has_many动态解决方案。我怎样才能做到这一点?

我正在使用Rails 5.1

1 个答案:

答案 0 :(得分:0)

has_many没有这样的功能,因为可以使用Rails团队的标准where子句来完成,请检查:

无需添加此功能。它已经在那里使用标准where子句
参考:
https://github.com/rails/rails/issues/3912

您可以执行以下操作:

已修改的查询

# @event.id refers to the value of 60
@volunteers = Volunteer.includes({ signups: [{position: [{ eventday: :event }] }] }, :event_survey_result).where(event_survey_results: { id:  @event.id })

志愿者模式:

class Volunteer < ApplicationRecord
  # No need to filter here, as you can filter it using standard where
  has_many :event_survey_results , class_name: 'Questionnaires::SurveyResult'

end