Skip to content

Instantly share code, notes, and snippets.

@claeusdev
Forked from query-string/posts_conttoller.rb
Last active February 11, 2022 02:24
Show Gist options
  • Save claeusdev/2b91384578ff321faebcb952608db8ce to your computer and use it in GitHub Desktop.
Save claeusdev/2b91384578ff321faebcb952608db8ce to your computer and use it in GitHub Desktop.
class PostController < ApplicationController
before_action :set_post
before_action :set_active_posts, only: [:create, :update]
def show
@post = @posts.find_by(slug: params[:slug])
@author = @post.author
if !@post.present?
render "errors/404.html", status: :not_found
end
if @author.inactive?
redirect_to posts_path
end
end
def index
@posts = Searcheable.new(params, @posts).search
@posts = @posts.page(params[:page]).per(20)
redirect_to blog_index_path unless @posts.size > 0
end
def breaking_news
@posts = @posts.breaking.page(params[:page]).per(20)
end
def update
redirect_to posts_path if !current_user.admin?
if @post.update(post_params)
redirect_to(@post)
else
render :edit, status: :unprocessable_entity
end
end
def preview
end
private
def posts_categories
post_categories = []
@posts.each do |post|
if get_categories.include?(post.category)
post_categories << post.category
end
end
post_categories
end
def set_post
@post = Post.active.find(params[:id])
end
def set_active_posts
@posts = Post.active.include(:author)
end
def post_params
params.require(:post).permit(:slug, :author_id) # rest of params go here
end
def get_categories
Category.visible.all
end
end
class Searchable
def initialize(params, posts)
@params = params
@posts = posts
end
def search
if @params[:before_date]
@posts = @posts.where("created_at > ?", @params[:before_date])
end
if @params[:q]
@q = @posts.ransack(@params[:q])
@posts = @q.result
end
@posts
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment