加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails,如何避免在关联中的总计(count,size,cou

发布时间:2020-12-16 22:00:23 所属栏目:百科 来源:网络整理
导读:我有这些机型: class Children ActiveRecord::Base has_many :tickets has_many :movies,through: :ticketsendclass Movie ActiveRecord::Base has_many :tickets has_many :childrens,through: :tickets belongs_to :cinemaendclass Ticket ActiveRecord::
我有这些机型:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读