[英]Access data from join-table in has_many :through, preventing additional data loading
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.distance
是ComputedValue.find(report_id: Report.first.id, settlement_id: Report.first.settlements.first.id).distance
有没有任何一种优雅而又快速的方法来使它起作用?
当我打电话Report.first.settlements.first
,Rails已经已经加载记录的第一份报告,第一个定居点和记录从加入表computed_values
。 如何防止从computed_values
进行第二次加载以查找值并使用已加载的记录中的数据?
好的,我找到了解决方案。
# Report
has_many :settlements, -> {select("settlements.*, computed_values.distance AS distance")},
through: :computed_values
之后, Report.first.settlements.first.distance
可以完美地工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.