Joe C
Joe C

Reputation: 1855

Rails can a class variable be assigned within a controller's instance method?

In Rails, can I create a class variable that can be shared between the different instance methods? Just trying to avoid an unnecessary call if possible. Sorry guys, taking this project over last minute from another developer. I haven't coded Rails in 2 years and excited to be getting back into it.

Here's example code:

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

Upvotes: 0

Views: 272

Answers (1)

Max Woolf
Max Woolf

Reputation: 4068

Your best bet here is to set up a before_action (or before_filter prior to Rails 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

Now you have access to @video_episode in both the index and show actions.

Upvotes: 1

Related Questions