Rails 4.1.7
I have 3 models.
# 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
has an attribute distance
.
I want to get such construction works: Report.first.settlements.first.distance
which is ComputedValue.find(report_id: Report.first.id, settlement_id: Report.first.settlements.first.id).distance
Is there any elegant and fast way to get that worked?
When I call Report.first.settlements.first
, Rails has already loaded records for first report, first settlement and record from join-table computed_values
. How to prevent second loading from computed_values
for finding values and use data from already loaded records?
Ok, I found a solution.
# Report
has_many :settlements, -> {select("settlements.*, computed_values.distance AS distance")},
through: :computed_values
After that, Report.first.settlements.first.distance
works just perfectly!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.