0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.