Last active
May 23, 2025 16:43
-
-
Save javierav/ee770365928cc179ea72efda3491eb88 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PostsController < ApplicationController | |
before_action :build_post, only: %i[index new create] | |
before_action :find_post, only: %i[show edit update destroy] | |
before_action :assign_attributes, only: %i[create update] | |
before_action :authorize_post, only: %i[new create show edit update destroy] | |
after_action :verify_authorized | |
after_action :verify_policy_scoped, only: :index | |
def index | |
@pagy, @posts = pagy(authorize policy_scope(scope).filtered_by(filter_params).order(order_params)) | |
end | |
def create | |
if @post.save | |
redirect_to @post | |
else | |
render :new, status: :unprocessable_entity | |
end | |
end | |
def update | |
if @post.save | |
redirect_to @post | |
else | |
render :edit, status: :unprocessable_entity | |
end | |
end | |
def destroy | |
if @post.destroy | |
redirect_to posts_path | |
else | |
redirect_to @post | |
end | |
end | |
private | |
def scope | |
Post | |
end | |
def build_post | |
@post = scope.build | |
end | |
def find_post | |
@post = policy_scope(scope).find(params[:id]) | |
end | |
def assign_attributes | |
@post.assign_attributes(permitted_attributes(@post)) | |
end | |
def authorize_post | |
authorize @post | |
end | |
def filter_params | |
params.permit() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment