在控制器操作轨道之间共享数据



>我有一个应用程序,它渲染一个div,里面有链接,它使用AJAX更新这个div的外观。 问题是 Rails 在切换视图时必须一遍又一遍地请求相同的数据,这似乎效率低下。

在阅读了在控制器操作之间共享变量的主题后,我了解到由于无状态的性质,这是不可能的。 还读过,session不应该用来存储对象,而这些变量包含大量的数据,主要用于生成图。 我想另一个选项是缓存,我不是很熟悉。 或者可能将变量保存在浏览器上的Javascript中。

有人有类似的问题可以提供一些指导吗?

class ArtistsController < ApplicationController
def index
if params[:term]
respond_to do |format|
format.html
format.js {render "show.js.haml"}
end
else
@artists= Artist.all
end
end
def show
@days=90
# DATABASE QUERIES
@artist= Artist.find(params[:id])
@reach_period= Reachupdate.period(@artist.id,@days)
@update_period=Update.period(@artist.id,@days)
@songs_load= Song.by_artist(@artist.id).joins(:playlists)
@song_period= @songs_load.period(@days)
# CHART
@updates= ChartTransformation::pop_chart(@update_period,@days)
@reach = ChartTransformation::reach_chart(@reach_period,@days)
@dates= ChartTransformation::dates(@days,3)
@reach_labels= ChartTransformation::reach_labels(@reach_period,2)
@songs= ChartTransformation::data_to_releases(@song_period, @days)
@reach_diff = Reachupdate.diff(@reach_period)
@pop_diff = Update.diff(@update_period)
@playlisting= ChartTransformation::playlisting(Playlist.by_artist(@artist.id),@days)
end
def overview
@days=90
# DATABASE QUERIES
@artist= Artist.find(params[:id])
@reach_period= Reachupdate.period(@artist.id,@days)
@update_period=Update.period(@artist.id,@days)
@song_period= Song.by_artist(@artist.id).period(@days) 
# CHART
@updates= ChartTransformation::pop_chart(@update_period,@days)
@reach = ChartTransformation::reach_chart(@reach_period,@days)
@dates= ChartTransformation::dates(@days,3)
@reach_labels= ChartTransformation::reach_labels(@reach_period,2)
@songs= ChartTransformation::data_to_releases(@song_period, @days)
@reach_diff = Reachupdate.diff(@reach_period)
@pop_diff = Update.diff(@update_period)
@playlisting= ChartTransformation::playlisting(Playlist.by_artist(@artist.id),@days)

respond_to do |format|
format.js {render "timeline_content.js.haml"}
end
end
end
我想

另一个选项是缓存,我不是很熟悉

您必须熟悉缓存。这是您问题的答案。

在您的情况下,它会在视图中执行片段缓存,请阅读指南 https://guides.rubyonrails.org/caching_with_rails.html#fragment-caching

最新更新