ruby-on-rails – Rails,如何避免在关联中的总计(count,size,counter_cache)的“N 1”查询?

我有这些机型:
class Children < ActiveRecord::Base
    has_many :tickets
    has_many :movies,through: :tickets
end


class Movie < ActiveRecord::Base
    has_many :tickets
    has_many :childrens,through: :tickets
    belongs_to :cinema
end


class Ticket < ActiveRecord::Base
    belongs_to :movie,counter_cache: true
    belongs_to :children
end


class Cinema < ActiveRecord::Base
    has_many :movies,dependent: :destroy
    has_many :childrens,through: :movies
end

我现在需要的是“电影院”的页面,我想打印这个电影院的孩子的总和(数量,大小?),所以我写道:

>在cinemas_controller.rb中:

@childrens = @ cinema.childrens.uniq

>在电影院/ show.html.erb:

<%@ childrens.each do | children | %><%= children.movi​​es.size%><%end%>

但显然我有弹珠宝,提醒我的Counter_cache,我不知道在哪里放这个counter_cache,因为电影的不同的id.

而且没有counter_cache,我不是我想要的,因为我想要一个数字,这个电影院里有多少孩子从这个电影院的许多日子里把他们从门票里拿走.

如何?

UPDATE

如果在我看来我使用这个代码

<% @childrens.each do |children| %>
  <%= children.movies.where(cinema_id: @cinema.id).size %>
<% end %>

宝石子弹不要说我什么,一切都正常工作.

我有一个问题:这种查询数据库的方式比较重,因为视图中的代码

解决方法

这可能会帮助你.
@childrens_count = @cinema.childrens.joins(:movies).group("movies.children_id").count.to_a

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...