2017-01-16 6 views
0

Railsでは、さまざまなインスタンスメソッド間で共有できるクラス変数を作成できますか?可能であれば、不必要な呼び出しを避けようとしています。申し訳ありませんが、他の開発者からこのプロジェクトを最後にやっています。私は2年後にRailsをコーディングしておらず、それに戻ってくることに興奮しています。今、あなたは両方で@video_episodeへのアクセス権を持っている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 

答えて

1

ここにあなたの最善の策は、before_action(またはbefore_filter 5をレールに前に)設定することです

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 

は、ここでのコード例ですindexおよびshowアクションです。

関連する問題