coderwannabe2
coderwannabe2

Reputation: 221

Devise before_action explanation

I am having trouble understanding this line that gets automatically generated in the controller when I install Devise:

before_action :set_post, only: [:show, :edit, :update, :destroy]

I tried reading the documentation but I am unable to make sense of what it does. For example what does the :set_post symbol do? What is it part of?

Any explanations or resources where I can go for further reading would be appreciated.

Upvotes: 1

Views: 1139

Answers (2)

Federico Toscano
Federico Toscano

Reputation: 101

Suppose you have a controller like this:

class PostController < ApplicationController
   def index
      @posts = Post.all
   end
   def show
      @post = Post.find(params[:id])
   end
   def edit
      @post = Post.find(params[:id])
   end
end

You see that in show and edit actions there is the same code, you're breaking the DRY principle, so to avoid code repetitions you set an action (method):

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

that will be performed before the actions that require that same code:

before_action :set_post, only: [:show, :edit, :update, :destroy]

In the end you'll have a controller like this:

class PostController < ApplicationController
   def index
      @posts = Post.all
   end
   def show
   end
   def edit          
   end

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

Upvotes: 4

DenisLukyanov
DenisLukyanov

Reputation: 11

:set_post - a method at the end of the controller.

The device does not have anything to do with

Upvotes: 1

Related Questions