【问题标题】:Access data from join-table in has_many :through, preventing additional data loading从 has_many :through 中的连接表访问数据,防止额外的数据加载
【发布时间】:2015-01-21 11:05:54
【问题描述】:

Rails 4.1.7

我有 3 个模型。

# Report
class Report < ActiveRecord::Base
  has_many :computed_values, dependent: :destroy
  has_many :settlements, through: :computed_values
end

# ComputedValue
class ComputedValue < ActiveRecord::Base
  belongs_to :report
  belongs_to :settlement
end

# Settlement
class Settlement < ActiveRecord::Base
  has_many :computed_values
  has_many :reports, through: :computed_values
end

ComputedValue 有一个属性distance

我想得到这样的建筑作品:Report.first.settlements.first.distanceComputedValue.find(report_id: Report.first.id, settlement_id: Report.first.settlements.first.id).distance

有什么优雅而快速的方法来实现它吗?

当我调用Report.first.settlements.first 时,Rails 已经从连接表computed_values 加载了第一个报告、第一个结算和记录的记录。 如何防止从computed_values 再次加载以查找值并使用已加载记录中的数据?

【问题讨论】:

    标签: mysql ruby-on-rails-4 activerecord


    【解决方案1】:

    好的,我找到了解决办法。

    # Report
    has_many :settlements, -> {select("settlements.*, computed_values.distance AS distance")},
              through: :computed_values
    

    之后,Report.first.settlements.first.distance 就完美运行了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      相关资源
      最近更新 更多