【发布时间】:2020-04-28 10:44:28
【问题描述】:
在我的应用程序中,我有一个如下所示的 search_volume.rb 模型:
search_volume.rb:
class SearchVolume < ApplicationRecord
# t.integer "keyword_id"
# t.integer "search_engine_id"
# t.date "date"
# t.integer "volume"
belongs_to :keyword
belongs_to :search_engine
end
keyword.rb:
class Keyword < ApplicationRecord
has_and_belongs_to_many :labels
has_many :search_volumes
end
search_engine.rb:
class SearchEngine < ApplicationRecord
belongs_to :country
belongs_to :language
end
label.rb:
class Label < ApplicationRecord
has_and_belongs_to_many :keywords
has_many :search_volumes, through: :keywords
end
在label#index 页面上,我试图显示用户cookie 的search_engine 上个月每个标签中关键字的search_volumes 总和。我可以通过以下方式做到这一点:
<% @labels.each do |label| %>
<%= number_with_delimiter(label.search_volumes.where(search_engine_id: cookies[:search_engine_id]).where(date: 1.month.ago.beginning_of_month..1.month.ago.end_of_month).sum(:volume)) %>
<% end %>
这很好,但我觉得上面的效率很低。使用目前的方法,我也觉得很难对搜索量进行操作。大多数时候我只想知道上个月的搜索量。
通常我会在关键字模型上创建一个 counter_cache 来跟踪最新的 search_volume,但由于有几十个 search_engine 我必须为每个创建一个,这也是低效的。
分别存储所有不同搜索引擎上个月搜索量的最有效方法是什么?
【问题讨论】:
标签: ruby-on-rails counter-cache