微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐