[英]Rails: Preloading a has_many through association
I have a Trailer model and each Trailer belongs_to a Movie, and a Movie has_many :releases. 我有一个预告片模型,每个预告片都属于电影,并且电影has_many:releases。 And Trailer has_many :releases through :movie 拖车has_many:通过:movie发布
Release has a column :medium which can be "Netflix", "Theater", or "Torrent". 发布有一个:medium列,可以是“ Netflix”,“ Theater”或“ Torrent”。
In my controller: 在我的控制器中:
@trailers = Trailer.all
In my view, I want to check the releases of each trailer: 我认为,我想检查每个预告片的发布情况:
<%= render @trailers %>
then: 然后:
if trailer.releases.where(medium:"Torrent").first
# show a Torrent icon
end
Is there a way to preload trailer.releases so that I'm not hammering the DB and calling trailer.releases.where(medium:"Torrent").first, trailer.releases.where(medium:"Netflix").first, trailer.releases.where(medium:"Theater").first
for each trailer that gets rendered? 有没有一种预加载trailer.releases的方法,这样我就不会锤打数据库并调用trailer.releases.where(medium:"Torrent").first, trailer.releases.where(medium:"Netflix").first, trailer.releases.where(medium:"Theater").first
对于每个渲染的预告片?
How do I optimize this? 我该如何优化呢?
Try in controller: 在控制器中尝试:
@trailers = Trailer.all # 1 query to DB
@movies_releases = %w(Torrent Netflix Theater).map do |medium|
[medium, Release.where(medium: medium).pluck('DISTINCT movie_id')]
end.to_h # 3 queries to DB
And then in view: 然后来看:
if @movies_releases['Torrent'].include?(trailer.movie_id)
# show a Torrent icon
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.