Search code examples
ruby-on-railsbefore-filter

Rails 3 load method before filter


What is the reason for using a before_filter :load?

def load
  @posts = Post.all
  @post = Post.new
end

What does this accomplish? I've just seen it done in a tutorial and don't understand if it's beneficial.


Solution

  • In this case the load method will be called for all method calls within the controller. Meaning @posts and @post will be available to all actions for said controller. It is very rare that I use them. Just calling load within the action that needs it and moving the load method to private should be good enough.

    If you wanted @posts and @post to be available for all the actions in the controller then this is an acceptable solution.

    You could always do before_filter :load, only: [:index]