0

我有一个Movie模型和一个MovieStream模型。关系是 Movie has_manyMediaType(和 MediaType belongs_toMovie)。

MediaType 有两个属性“url_broken”(真/假)和“dvd”(真/假)。

在我看来,我有:

Movie.all.includes(:movie_item).each do |movie|
  render partial: 'movie_item'
end

movie_item-部分我有(简化):

<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 %>

这(显然)会导致 N+1 个查询,但我看不到任何解决方法。是否有可能以某种方式以我可以同时获得streamsand的方式查询视图查询dvds

喜欢:

Movie.all.join_stream_something.each do |movie, streams, dvds|
render partial: 'movie_item', :locals => { :movie => movie, :streams => streams, :dvds => dvds}
end

没有N+1?结尾

4

2 回答 2

1

has_many你可以在电影类中定义一个作用域

class Movie < ApplicationRecord
  has_many :valid_url_media_types, -> { where(url_broken: false) }, class_name: "MediaType"
  has_many :not_dvd_media_types, -> { where(dvd: false) }, class_name: "MediaType"
  has_many :dvd_media_types, -> { where(dvd: true) }, class_name: "MediaType"
end

那么在你看来

Movie.all.includes(:valid_url_media_types, :not_dvd_media_types, :dvd_media_types).each do |movie|
  render partial: 'movie_item', movie: movie
end

你的部分:

<h1><%= movie.title %></h1>

<% if movie.valid_url_media_types.blank? %>
  No media types exist
<% else %>
<h2>Streams</h2>
<% streams = movie.not_dvd_media_types.each do |media_type| %>
  * <%= media_type.name %>
<% end %>

<h2>Dvd's</h2>
<% dvds = movie.dvd_media_types.each do |media_type| %>
  * <%= media_type.name %>
<% end %>
于 2021-04-11T12:00:32.580 回答
0

看起来你只需要使用.includes

https://apidock.com/rails/ActiveRecord/QueryMethods/includes

Movie.includes(:media_type).all.each do |movie|
  render partial: 'movie_item', :locals => { :movie => movie }
end
于 2021-04-08T02:07:44.163 回答