【发布时间】:2015-09-21 13:07:09
【问题描述】:
我有这些型号:
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.movies.size %><% end %>
但显然我有子弹 gem 提醒我 Counter_cache 并且我不知道将这个 counter_cache 放在哪里,因为电影的 id 不同。
而且,如果没有 counter_cache,我所拥有的也不是我想要的,因为我想计算那家电影院有多少孩子从那家电影院的票中拿走他们。
怎么做?
更新
如果在我看来我使用此代码:
<% @childrens.each do |children| %>
<%= children.movies.where(cinema_id: @cinema.id).size %>
<% end %>
gem bullet 什么都没说,一切正常。
但是我有一个问题:这种查询数据库的方式因为视图中的代码比较重?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord relationship