Reputation: 221
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
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
Reputation: 11
:set_post - a method at the end of the controller.
The device does not have anything to do with
Upvotes: 1