我有一个周期性的视图,其中select标签的数据不经常变化但是很昂贵,所以我想实现缓存,它适用于一些选择,但不要知道如何使用grouped_collection_select。
这是我想要缓存的代码(抱歉西班牙语的变化):
模型代码:
def self.cached_campuses
Rails.cache.fetch([self, "campuses"]) do
Campus.active.order(:name)
end
end
def self.cached_programas
Rails.cache.fetch([self, "programas"]) do
Programa.considered.active.order(:name).map{ |programa| [programa.name, programa.id, {'data-campus'=>programa.campus.id, 'data-nivel'=>programa.nivel.clave}] }
end
end
#there are more but of the same style
控制器:
@campus = Campus.cached_campuses
@programas = Programa.cached_programas
# some others
查看:
= simple_form_for @user do |f|
# This reads from cache everything
= f.input :campus_id, collection: @campus, ...
# This one doesn't read all from cache, makes queries to the table Nivel cause the grouped_collection
= f.grouped_collection_select :nivel_id, @campus, :niveles, ...
# This reads from cache everything
= f.select :programa_id, options_for_select( @programas )
# some other selects
我需要select with grouped_collection,因为在View中它会通过javascript过滤,具体取决于用户在顶部选择中选择的选项。
如何在模型内部缓存Nivel groups_collection_select的数据?
答案 0 :(得分:1)
找到它,
而不是groups_collection_select,在Helper中我做了:
def cached_niveles
unless Rails.cache.exist?( "select_niveles" )
Rails.cache.write( "select_niveles", option_groups_from_collection_for_select(Campus.cached_campuses, :niveles, :id, :clave, :nombre) )
end
Rails.cache.read( "select_niveles")
end
形式:
= select_tag 'usuario[nivel_id]', cached_niveles, prompt: "NIVEL DE INTERÉS"
诀窍是使用option_groups_from_collection_for_select