I have a Movie
model and a MovieStream
model. The relation is Movie has_many
MediaType (and MediaType belongs_to
Movie).
MediaType has two attribues "url_broken" (true/false) and "dvd" (true/false).
In my view I have:
Movie.all.each do |movie| render partial: 'movie_item' end
and in movie_item
-partial I have (simplified):
<h1><%= movie.title %></h1> <% if movie.media_types.where(:url_broken => false).blank? %> No media types exist <% else %> <h2>Streams</h2> <% streams = movie.media_types.where(:dvd => false).each do |media_type| %> * <%= media_type.name %> <% end %> <h2>Dvd's</h2> <% dvds = movie.media_types.where(:dvd => true).each do |media_type| %> * <%= media_type.name %> <% end %>
This (obviously) causes N+1 queries but I cannot see any way around it. Is it possible, in some way, to query the view-query in a way that I can get the streams
and dvds
at the same time?
Like:
Movie.all.join_stream_something.each do |movie, streams, dvds| render partial: 'movie_item', :locals => { :movie => movie, :streams => streams, :dvds => dvds} end
to not have N+1? end
https://stackoverflow.com/questions/66995016/smart-way-of-not-getting-n1-while-querying-has-many-relationship-in-rails April 08, 2021 at 06:37AM
没有评论:
发表评论