New in Rails 4.0: Shared Record Pattern in Controllers

Rails 4.0 will encourage developers to use the shared record pattern in controllers. Scaffold generators in Rails 4.0 will use by default. Here's an example of using the pattern.

class PostController < ActionController::Base
  before_action :set_post, except: [:index, :new, :create]

  def show
    # do something with @post
  end

private
    def set_post
      @post = Post.find(params[:id])
    end
end

Basically, instead of calling Post.find(params[:id]) in show, edit, update and delete actions manually, you do it once in the set_post method.

Attentive readers may have noticed another change: before_filter will be called before_action in Rails 4.0.

You're the 9669th person to read this article.