我有索引和显示方法,像下面是有可能在多个动作中使用的变量值
def index
@variable = SomeModel.includes(:some_other_model)
end
def show
@variable = SomeModel.includes(:some_other_model).find_by!(id: params[:id])
end
所以SomeModel.includes(:some_other_model)
是在这两个行为普遍,我在做加盟的some_other_model索引和显示方法
,所以我认为让这样做before_action将其移动到一个私有方法
before_action :set_something, only: [:index, :update]
def index
@variable
end
def show
@variable.find_by!(id: params[:id])
end
private
def set_something
@variable = SomeModel.includes(:some_other_model) if @variable.nil?
rescue ArgumentError => e
render_error(:bad_request, e.message)
end
所以我的问题是,有没有什么办法可以存储@var当索引或显示被调用时的可用值,以及下一次调用其他操作时是否使用相同的@变量值,而不是再次访问数据库?
谢谢。所以只是好奇,我们不能实现使用类实例变量呢? –
@ Nick.S .:查看更新:) –
不错。谢谢你的帮助。 –