【问题标题】:Preload dynamically filtered has_many association with ActiveRecord预加载与 ActiveRecord 的动态过滤的 has_many 关联
【发布时间】:2018-01-07 20:49:18
【问题描述】:

我正在尝试包含/预加载具有动态运行时条件的 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

【问题讨论】:

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


    【解决方案1】:

    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
    

    【讨论】:

    • 我已经尝试过了,但如果志愿者没有 event_survey_result,他就不会包含在@volunteers 中。这应该是一个左连接,但它不像它。
    • 这是我正在阅读的解释问题的文章。最后,它解释了左连接的问题,如果右表上缺少记录,则从左表中排除记录。 revs.runtime-revolution.com/…
    猜你喜欢
    • 2014-07-08
    • 2011-09-28
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多