在Rails中,我可以创建一个可以在不同实例方法之间共享的类变量吗?如果可能的话,尽量避免不必要的电话。对不起,伙计们,从最后一分钟开始,这个项我还没有在2年内对Rails进行编码,并很高兴能够重新使用它。
以下是示例代码:
class Api::VideoEpisodesController < Api::ApiController
# GET /video_episodes
# GET /video_episodes.json
def index
# can I share @@video_episodes with the set_video_episode method?
# or just @video_episodes = VideoEpisode.where(season_number: params[:season_number]) because can't do what I intend?
@@video_episodes = VideoEpisode.where(season_number: params[:season_number])
end
# GET /video_episodes/1
# GET /video_episodes/1.json
def show
set_video_episode
end
private
# Use callbacks to share common setup or constraints between actions.
def set_video_episode
# would I be able to access @@video_episodes from the index method or
# is the best way to go instance variable:
# @video_episodes = VideoEpisode.where(season_number: params[:season_number])
# @video_episode = @video_episodes.find(params[:id])
@video_episode = @@video_episodes.find(params[:id])
end
end
答案 0 :(得分:1)
这里最好的选择是在Rails 5之前设置before_action
(或before_filter
。)
class Api::VideoEpisodesController < Api::ApiController
before_action :set_video_episode, only: [:index, :show]
def index
end
def show
end
private
def set_video_episode
@video_episode = VideoEpisode.find(params[:id])
end
end
现在,您可以在@video_episode
和index
操作中访问show
。